Reputation: 1666
I find an existing record like so:
$m = new Model();
$value = 1;
$m->whereField($field)->first(); // Get the model
if ($m->exists()) { // this is true so I know it's there
$m->anotherField = $value
$m->save(); // Laravel tries to INSERT vs UPDATE. Why????
}
I know the record can be found because exists()
is true. Yet I try to save it and Laravel treats it like a brand new record and tries to insert instead of update. What did I do wrong here?
Upvotes: 3
Views: 778
Reputation: 63
You could also do:
$m = $m->whereField($field)->firstOrFail();
//catch exception... (log or something else)
$m->anotherField = $field;
$m->save();
Doing this will let you catch the exception so you can log and display an error page as necessary. To catch the ModelNotFoundException, add some logic to your app/Exceptions/Handler.php file.
http://laravel.com/docs/5.0/eloquent
Upvotes: 1
Reputation: 73251
You need to set a variable to the found item
$m = $m->whereField($field)->first();
if ($m->exists()) {
$m->anotherField = $value;
$m->save();
}
As you have it now, $m
is only refering to new Model()
, not to the found item.
Upvotes: 4