When can the eloquent laravel save () collection go wrong?

I want to know the possible errors or exception that elqouent save() may cause. In laravel, I do as shown below 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 do not prefer the save() environment to the if to check if the model is saved. If this throws an exception, I would love to try..catch it in a try..catch block, for example,

  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 eloquent collection save() go wrong? Or am I just thinking about it?

+5
source share
2 answers

The only exceptions I came across were when I set foreign key constraints and broke them in my code (or by the user) that would throw a QueryException in a 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 to explicitly throw exceptions, I can think of two ways:

  • Extend the base model and override the save() method so that if it returns false, it will throw its own exception for you.

  • To expand and instead of overriding name the saveOrFail() method.

  • Use this library method saveOrFail() (which does the same as # 1) but is distracted ( https://github.com/dwightwatson/validating ).

+4
source

Can laravel's eloquent save () collection go wrong?

Yes, behind the scenes, the save method raises several model events such as creation and saving, which returns false if something goes wrong. Event Details

If something goes wrong, Laravel App :: error will handle exceptions for you.

 App::error(function(Exception $exception, $code) { }); 
0
source

Source: https://habr.com/ru/post/1203386/


All Articles