laravel save()方法是否抛出异常?

时间:2018-12-11 12:57:26

标签: php database laravel exception-handling transactions

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

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()函数不成功,它本身是否会引发异常?

2 个答案:

答案 0 :(得分:3)

我知道这个问题已经有了答案,但是对于那些偶然发现并希望抛出异常的人来说,您可以使用方法 saveOrFail() 而不是 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()
    );
}

此方法至少从 Laravel 5.5 开始就存在,您可以在 docs

中找到有关它的更多信息

答案 1 :(得分:1)

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