Laravel中try catch异常处理和事务回滚

KarlXu 2017-03-15 13:03:06原创浏览量2467
use Illuminate\Support\Facades\DB;
use App\Http\Model\User;


$data = [
   'nickname' => 'test',
   'gender' => 0,
];

$data2 = [
   'nickname' => 'test2',
];

DB::beginTransaction();  //开启事务

User::insertGetId($data);  //插入数据

//捕捉异常
try {
   $id = User::insertGetId($data2); //插入第二条数据并提交
   DB::commit();
}catch (\Exception $e){
   DB::rollBack(); //异常则回滚并报错
   return response()->json(['error',$e->getMessage()]);
}

有问题请Email联系: karlxu0424@gmail.com