Reputation: 1536
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?
Upvotes: 3
Views: 5196
Reputation: 41
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
Upvotes: 4
Reputation: 491
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.
Upvotes: 4