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

Does laravel save() method throws exception?

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

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() 函数不成功,它自己会抛出异常吗?

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

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

中找到有关它的更多信息