3

I have a little question here. This is my code:

DB::beginTransaction();
    try{
        $created = new TransportTypeColumn();
        $created->name = $translated_ids[0];
        if(!$created->save())
            throw new \Exception("failed saving transport type column");
        DB::commit();
        return response()->json(['success'=>'Property has been created successfully', 'data'=>$created],200);

    }catch(\Exception $e){
        DB::rollback();
        return response()->json(['error'=>'Something went wrong, please try later.'], 500);
    }

so do I need this piece of code ? :

if(!$created->save())
            throw new \Exception("failed saving transport type column");

or does it throws exception itself if save() function doesn't succeed?

O. Shekriladze
  • 1,346
  • 1
  • 19
  • 36
  • Possible duplicate of [Check if laravel model got saved or query got executed](https://stackoverflow.com/questions/27877948/check-if-laravel-model-got-saved-or-query-got-executed) – Walter Cejas Dec 11 '18 at 12:59
  • You can set `$saved = $created->save(); $saved === true;`. – Tpojka Dec 11 '18 at 15:04

2 Answers2

4

save returns a boolean, you need to check if the save was successfull or not, but unless there is a mysql error you won't get any exceptions.

  • 1
    If save() doesn't work, that means there is mysql error? so I always get exception.. isn't that right? – O. Shekriladze Dec 11 '18 at 13:02
  • 1
    I mean is it possible that save() returns false but there is no mysql or any other exceptions? – O. Shekriladze Dec 11 '18 at 13:03
  • I can't think of one right now, but i found this https://laravel.io/forum/09-08-2014-save-function-doesnt-work-and-does-not-output-an-error , it is always good to check if the record was saved anyway. – Munteanu Petrisor Dec 11 '18 at 13:09
4

I know this question has already an answer, but for people who stumble upon this and want an exception to be thrown, you could use the method saveOrFail() instead of save().

DB::beginTransaction();
try{
    $created = new TransportTypeColumn();
    $created->name = $translated_ids[0];
    $created->saveOrFail();
    
    DB::commit();
    return response()->json(['success'=>'Property has been created successfully', 'data'=>$created],200);
} catch(\Exception $e) {
    DB::rollback();
    return response()->json(
        ['error'=>'Something went wrong, please try later.'],
        $e->getCode()
    );
}

This method is around since at least Laravel 5.5 and you can find more information about it in the docs

Sebb
  • 41
  • 2