我有许多不同的位置方式来插入和更新我的数据库,我希望能够在插入数据库之前对用户输入进行 trim()。我知道在模型中我可以做类似下面的事情,但我不想对每个领域都这样做。有没有办法设置适用于所有字段的通用 setter ?

例子:

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

最佳答案

您可能能够覆盖这些方法:

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

而且您永远不应再次获得未修剪的值(value)。

编辑:

在这里测试,我没有空格:
Route::any('test', ['as' => 'test', function()
{
    $d = Post::find(2);

    $d->title_en = "  Markdown Example  ";

    dd($d);
}]);

关于php - Laravel 的全局 Mutator,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23567652/

10-14 13:04
查看更多