Home > Mobile >  The Laravel $model->save() response?
The Laravel $model->save() response?

Time:06-25

If you are thinking this question is a beginner's question, maybe you are right. But really I was confused.

In my code, I want to know if saving a model is successful or not.

$model = Model::find(1);
$model->attr = $someVale;
$saveStatus = $model->save()

So, I think $saveStatus must show me if the saving is successful or not, But, now, the model is saved in the database while the $saveStatus value is NULL.

I am using Laravel 7;

CodePudding user response:

save() will return a boolean, saved or not saved. So you can either do:

$model = new Model();
$model->attr = $value;
$saved = $model->save();
if(!$saved){
    //Do something
}

Or directly save in the if:

if(!$model->save()){
    //Do something
}

CodePudding user response:

Please read those documentation from Laravel api section.

https://laravel.com/api/5.8/Illuminate/Database/Eloquent/Model.html#method_getChanges

From here you can get many option to know current object was modified or not.

Also you can check this,

Laravel Eloquent update just if changes have been made

For Create object, those option can helpful,

You can check the public attribute $exists on your model

if ($model->exists) {
// Model exists in the database
}

You can check for the models id (since that's only available after the record is saved and the newly created id is returned)

if(!$model->id){
App::abort(500, 'Some Error');
}
  • Related