Home » Php » php – Global Mutator for Laravel

php – Global Mutator for Laravel

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have many different locations ways of inserting and updating my database and I would like to be able to trim() the users input before inserting into the database. I know in the model I can do something like below, but I do not want to do this for every field. Is there a way to set a generic setter that works on all fields?

Example:

public function setSomFieldAttribute($value) {
     return $this->attributes['some_field'] = trim($value);
}
How to&Answers:

You probably will be able to override those 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 an untrimmed value again.

EDIT:

Tested this here and I got no spaces:

Route::any('test', ['as' => 'test', function()
{
    $d = Post::find(2);

    $d->title_en = "  Markdown Example  ";

    dd($d);
}]);

Answer:

Use Model Events for this and run trim on each field you want when creating or updating a model.

class Model extends \Eloquent {
    ...
    public static function boot() {
        parent::boot();

        static::saving(function($model){
            $model->some_field = trim($model->some_field);
        });
    }
    ...
}

Example usage:

$model = new Model;
$model->some_field = '  foobar    ';
$model->save();

// $model->some_field should now be trimmed