j. marc
j. marc

Reputation: 371

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

Upvotes: 10

Views: 11462

Answers (3)

Stefan Rubelov
Stefan Rubelov

Reputation: 1

I had a similar problem and after many many hours of pulling my hair I finally found the culprit.

Turns out the query was using the global scope I had set on the model. Even though the (eloquent) query is updating/creating it still uses the global scopes you have set up.

So, adding withoutGlobalScope(YourGlobalScope::class) before the updateOrCreate() method fixed my issue. Hope this helps someone and saves you few hours of debugging!

Upvotes: 0

Jorge Luis Romano
Jorge Luis Romano

Reputation: 161

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.

Upvotes: 14

j. marc
j. marc

Reputation: 371

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';

Upvotes: 10

Related Questions