Created
December 28, 2019 05:54
-
-
Save sushant-jadhav/b56049764d6e49070206de43bd44b5c9 to your computer and use it in GitHub Desktop.
Database Transaction in Laravel controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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