Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Database Transaction in Laravel controller
public function create(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => 'required|unique:users|max:255',
'email' => 'required|unique:users|max:255',
'amount' => 'required',
]);
if ($validator->fails()) {
return redirect()->route('user.index')
->withErrors($validator)
->withInput();
}
DB::beginTransaction();
try{
// Step 1 : Create User
$user = new User();
$user->email = $request->email;
$user->username = $request->username;
$user->save();
//Step 2 : Stripe Api Call
//Step 3 : Amount Charged
$user_amount = new UserSubscriptionAmount();
$user_amount->user_id = $user->id;
$user_amount->amount = $request->amount;
$user_amount->save();
DB::commit();
return redirect()->route('user.index')->with('success','Thank You for your subscription');
}catch(\Exception $e){
DB::rollback();
return redirect()->route('user.index')
->with('warning','Something Went Wrong!');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.