Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent updateOrCreate not updating

I am having trouble using updateOrCreate.

The below code is SUCCESSFULLY creating a new row; however when it comes to updating an existing row it doesn't work at all!

comm_helpful::updateOrCreate(
           ['ID' => 1],
           ['time' => 3000]
        );

This works exactly as expected:

comm_helpful::where('ID', 1)->update(['time' => 3000]);

I've stripped the examples above back to bare minimums (which I did as part of debugging) and it's still not working!!

like image 468
j. marc Avatar asked Dec 05 '17 11:12

j. marc


2 Answers

I have a similar problem. My model had:

protected $fillable = ['user_x_cliente_id','internet_cliente_id'];

The status has 0.

              $habilita = leilao_habs::updateOrCreate(
                  [
                    'user_x_cliente_id' => $user_x_cliente->id,
                    'internet_cliente_id' => $int_cli->id
                  ],
                  ['status' => 1]
               );

               dd($habilita);

After execute the updateOrCreate , the status still 0 and No get MassAssignmentException error.

The solution was change the model adding the status to protected $fillable:

protected $fillable = ['user_x_cliente_id','internet_cliente_id','status'];

Now the updateOrCreate works changing the status.

like image 150
Jorge Luis Romano Avatar answered Oct 18 '22 20:10

Jorge Luis Romano


Ok, after almost completely pulling my hair out; I found the problem where Eloquent is setting:

protected $primaryKey = 'id';

which is used on the update method and returned by getKeyName().

protected function setKeysForSaveQuery(Builder $query)
{

    $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());

    return $query;
}

I then realised my 'id' on the tale was uppercase and not lower case!

I guess that means my answer is that I need to ensure I am using lowercase 'id' for the primary key or overriding it on the Model

protected $primaryKey = 'ID';
like image 37
j. marc Avatar answered Oct 18 '22 20:10

j. marc