Global Mutator for Laravel

送分小仙女□ 提交于 2021-01-27 04:12:50

问题


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);
}

回答1:


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);
}]);



回答2:


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


来源:https://stackoverflow.com/questions/23567652/global-mutator-for-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!