Search code examples
phplaraveleloquentslim

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


Solution

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