首页 > 解决方案 > laravel save() 方法会抛出异常吗?

问题描述

我在这里有一个小问题。这是我的代码:

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);
    }

那我需要这段代码吗?:

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

或者如果 save() 函数不成功,它会自己抛出异常吗?

标签: phpdatabaselaravelexception-handlingtransactions

解决方案


save返回一个布尔值,您需要检查保存是否成功,但除非有 mysql 错误,否则您不会收到任何异常。


推荐阅读