Global mutator for Laravel

I have many different places to insert and update my database, and I would like to be able to trim() enter users before inserting into the database. I know that in the model I can do something like below, but I do not want to do this for each field. Is there a way to install a common setter that works in all fields?

Example:

 public function setSomFieldAttribute($value) { return $this->attributes['some_field'] = trim($value); } 
+6
source share
2 answers

You can probably override these methods:

 <?php class Post extends Eloquent { protected function getAttributeValue($key) { $value = parent::getAttributeValue($key); return is_string($value) ? trim($value) : $value; } public function setAttribute($key, $value) { parent::setAttribute($key, $value); if (is_string($value)) { $this->attributes[$key] = trim($value); } } } 

And you should never get the raw value again.

EDIT:

Tested here and I did not get spaces:

 Route::any('test', ['as' => 'test', function() { $d = Post::find(2); $d->title_en = " Markdown Example "; dd($d); }]); 
+3
source

Use Model Events for this and run trim in each field that you want to create or update a model.

 class Model extends \Eloquent { ... public static function boot() { parent::boot(); static::saving(function($model){ $model->some_field = trim($model->some_field); }); } ... } 

Usage example:

 $model = new Model; $model->some_field = ' foobar '; $model->save(); // $model->some_field should now be trimmed 
+5
source

All Articles