Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updateOrCreate does not work in Laravel Eloquent

I want to update or create a model. It's not working at all.

Here is my code:

foreach ($ProfileRequest as $fieldname => $value){
    ProfileRequest::updateOrCreate(['sm_id' => $uid, 'field_name' => $fieldname],
        [
            'sm_id' => $uid,
            'field_name' => $fieldname,
            'value' => $value
        ]);
    }

This is working for insertion:

 foreach ($ProfileRequest as $fieldname => $value) {
     $req = new ProfileRequest;
     $req->chef_id = $uid;
     $req->field_name = $fieldname;
     $req->value = $value;
     $req->save();
 }
like image 385
Manish Jakhmola Avatar asked Feb 28 '17 09:02

Manish Jakhmola


2 Answers

You need to specify the fillable fields in your model since you are dealing with Mass Updates. Put this at your model

protected $fillable = ['field_name','value'];
like image 112
redfades Avatar answered Sep 27 '22 19:09

redfades


Change your code like this

foreach ($ProfileRequest as $fieldname => $value){
    ProfileRequest::updateOrCreate(
        [
            'sm_id' => $uid
        ], 
        [
            'field_name' => $fieldname,
            'value' => $value
        ]
    );
}

Avoid repeating the fields. If somehow, my code doesn't work for you, please go check the function definition for yourself here: https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Builder.html#method_updateOrCreate

like image 37
EddyTheDove Avatar answered Sep 27 '22 20:09

EddyTheDove