I want to know the possible errors or exception that a elqouent's save()
could throw. In laravel, I have been doing like following when saving or updating a model.
// create or update some data
if($model->save()){
// continue
return true;
}
throw new Exception('Model could not be saved');
I don't prefer surrounding save()
with the if
statement to check if model is saved or not. If it throws an exception then, I would love to wrap it in try..catch
block like,
try{
// create or update some data
$model->save()
// continue
return true;
catch(SomeException $e){
throw new Exception('Model could not be saved');
}
So, Can laravel's eloquent collection save()
go wrong? Or, I am just over thinking about it?
The only exceptions I have encountered is when I have set foreign key constraints and broke them in my code (or by the user), which will throw a QueryException in the form like this:
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ...
If you want explicit exception throwing, I can think of 2.5 ways:
Extend from a base model and override the save()
method so that if it returns false, it throws its own exception for you to catch.
Extend and instead of overriding, name the method saveOrFail()
.
Use this library's saveOrFail()
method (which does the same as #1) but abstracted away (https://github.com/dwightwatson/validating).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With