Peter Jack
Peter Jack

Reputation: 867

Laravel set Attribute not working

i need 2 function add and update the user socials with serialize array to string before insert to database here my code

    <?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 !

Upvotes: 0

Views: 15778

Answers (1)

aceraven777
aceraven777

Reputation: 4556

I think it doesn't work on insert method. Try to use the create method to insert data to database.

$user = User::create($request->post);

Upvotes: 8

Related Questions