Juliatzin del Toro Juliatzin del Toro - 1 month ago 84x
PHP Question

Now save() return false in Laravel 5.3

About one change of Laravel 5.3,

Now, I have a model I want to save.

Before, I was doing :

$result = $model->save();

And I could know if operation is successful.

Now, with the new:

The Eloquent save method now returns false if the model has not been changed since the last time it was retrieved or saved.

mentioned in the upgrade guide

If the model has not changed, it return false.

Now my code tell me there were an error, because I trust true or false to be the result of good or bad operation.

So now, How can I check that save() was successful, even if it didn't change data???


Check if your model is Dirty.

//               A                    B
$result = !$model->isDirty() || $model->save()
  • If your model was modified, A will be false, but B should be true. So $result will be true
  • If your model was not modified, A will be true, so $result will be true.
  • If your model was modified and didn't saved sucessfull, you will get false both in A and B, so $result will be false.

I explain: This happens because Eloquent just do an DB query IF something changed. Laravel developers decided to change the save() response, so now you can know if a query was made, or if anything changed.