如何填充 laravel 模型中的字段,即使该字段不在表单请求中
How to populate a field in a laravel model even if the field it's not in the form request
抱歉标题乱七八糟。
所以,我有一个基本的用户模型,我正在尝试注册一个新用户,这是我在用户领域的一个领域 table 是我想要的 'screen_name'将使用名称属性中的第一个 'word' 自动归档。
我该怎么做?
我试过了
public function setScreenNameAttribute($value){
return 'MyFirstName';
}
但据我所知,set***Attribute 只有在我的表单请求中有这个字段时才会被触发,但我不希望用户填写这个字段我希望模型通过是自己的。
型号
public function setScreenNameAttribute($value)
{
$this->attributes['screen_name'] = strtolower(strtok($value, ' ')); // First name from the full name as screen name
}
控制器
$user->screen_name = 'John Smith'; // your request value goes here - $request->full_name;
您不需要在表单中为此设置字段。
希望这对您有所帮助。
如果不起作用请告诉我。
更新/另一个解决方案。
protected $attributes = array(
'screen_name' => 'Your name' // Any values
);
public function __construct(array $attributes = array())
{
$this->setRawAttributes(array(
'screen_name' => strtolower(strtok($attributes->first_name, ' '));
), true);
parent::__construct($attributes);
}
抱歉标题乱七八糟。
所以,我有一个基本的用户模型,我正在尝试注册一个新用户,这是我在用户领域的一个领域 table 是我想要的 'screen_name'将使用名称属性中的第一个 'word' 自动归档。
我该怎么做?
我试过了
public function setScreenNameAttribute($value){
return 'MyFirstName';
}
但据我所知,set***Attribute 只有在我的表单请求中有这个字段时才会被触发,但我不希望用户填写这个字段我希望模型通过是自己的。
型号
public function setScreenNameAttribute($value)
{
$this->attributes['screen_name'] = strtolower(strtok($value, ' ')); // First name from the full name as screen name
}
控制器
$user->screen_name = 'John Smith'; // your request value goes here - $request->full_name;
您不需要在表单中为此设置字段。
希望这对您有所帮助。
如果不起作用请告诉我。
更新/另一个解决方案。
protected $attributes = array(
'screen_name' => 'Your name' // Any values
);
public function __construct(array $attributes = array())
{
$this->setRawAttributes(array(
'screen_name' => strtolower(strtok($attributes->first_name, ' '));
), true);
parent::__construct($attributes);
}