Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what cases can the laravel's eloquent collection save() go wrong?

Tags:

php

laravel

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?

like image 361
user4055288 Avatar asked Sep 25 '14 11:09

user4055288


1 Answers

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:

  1. 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.

  2. Extend and instead of overriding, name the method saveOrFail().

  3. Use this library's saveOrFail() method (which does the same as #1) but abstracted away (https://github.com/dwightwatson/validating).

like image 99
Tony Avatar answered Oct 21 '22 12:10

Tony