全局变异器适用于Laravel

7
我有许多不同的方法可以插入和更新我的数据库,我希望能够在将用户输入插入到数据库之前trim()。 我知道在模型中,我可以做类似下面的事情,但是我不想为每个字段都这样做。 有没有一种通用的设置器,可适用于所有字段?
public function setSomFieldAttribute($value) {
     return $this->attributes['some_field'] = trim($value);
}

在最近的 Laravel 版本(>=5.4),有一个中间件可以直接修剪所有输入。https://laravel-news.com/laravel-5-4-middleware - George D.
2个回答

6

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

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

现在你再也不会得到未修剪的值了。

编辑:

我在这里测试过,没有空格:

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

    $d->title_en = "  Markdown Example  ";

    dd($d);
}]);

setAttribute 函数似乎没有执行。 - arrowill12
当使用类似于这样的东西时,这是否有效:$callback->where('id', $id)->update(array($field => $value, 'modified_by' => $user['username'], 'modified_date' => $currentTime)); 我唯一能想到的是我的更新方法不受变形器支持。 - arrowill12
可能不会,因为您正在从该语句生成查询。我认为在这种情况下它不会使用mutators,其中一部分工作由Query Builder完成,与Eloquent几乎没有任何关系。 - Antonio Carlos Ribeiro
只有在手动更新值时才需要使用 $model->value = new value。我想是这样的。 - Antonio Carlos Ribeiro

6
使用模型事件,在创建或更新模型时对每个需要的字段运行trim函数。
class Model extends \Eloquent {
    ...
    public static function boot() {
        parent::boot();

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

示例用法:

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

// $model->some_field should now be trimmed

1
@arrowill12 对我来说,这个答案应该被接受。 - Limon Monte

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接