Laravel全球突变体 [英] Global Mutator for Laravel
本文介绍了Laravel全球突变体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有许多不同的位置来插入和更新数据库,并且我希望能够 trim()
用户输入的内容在插入数据库之前.我知道在模型中我可以执行以下操作,但是我不想在每个领域都执行此操作.有没有一种方法可以设置适用于所有字段的通用设置器?
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?
示例:
public function setSomFieldAttribute($value) {
return $this->attributes['some_field'] = trim($value);
}
推荐答案
您可能将能够覆盖这些方法:
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.
在这里对此进行了测试,但我没有空格:
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);
}]);
这篇关于Laravel全球突变体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文