Laravel 设置属性不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44274295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel set Attribute not working
提问by Peter Hyman
i need 2 function add and update the user socials with serialize array to string before insert to database here my code
我需要 2 个函数添加和更新用户社交与序列化数组到字符串之前插入到数据库这里我的代码
<?php
use Illuminate\Database\Eloquent\Model as Model;
class User extends Model{
protected $table = 'user';
protected $primaryKey = 'user_id';
protected $fillable = [
'name',
'email',
'socials',
];
public function getSocialsAttribute($value){
return unserialize($value);
}
public function setSocialsAttribute($value){
settype($value, 'array');
$this->attributes['socials'] = serialize($value);
}
}
and in my controller
在我的控制器中
$user_id = User::insert($request->post);
the post array with
帖子数组与
array(
'name'=>'A',
'email'=>'[email protected]',
'socials'=> array(
'facebook' => 'facebook.com',
'twitter' => 'twiter.com'
)
)
but the database does not serialize the data !
但是数据库不会序列化数据!
回答by aceraven777
I think it doesn't work on insert
method. Try to use the create
method to insert data to database.
我认为它在insert
方法上不起作用。尝试使用该create
方法将数据插入数据库。
$user = User::create($request->post);