Last active
November 28, 2021 23:58
-
-
Save EricMcWinNer/120b561161536f6c7684813fc4740a51 to your computer and use it in GitHub Desktop.
Basic code snippet setting up a database transaction using DB facade methods
This file contains hidden or 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
<?php | |
namespace App\Controllers; | |
use App\Models\User; | |
use App\Models\Verification; | |
use Illuminate\Support\Facades\DB; | |
use Illuminate\Http\Request; | |
class ExampleController extends Controller { | |
public function registerUser(Request $request) { | |
try { | |
DB::beginTransaction(); // Tell Laravel all the code beneath this is a transaction | |
$user = User::create($request->all()); | |
Verification::create([ | |
'user_id' => $user->id, | |
'code' => str_pad(random_int(0, 9999), "4", "0", STR_PAD_LEFT), | |
'expires_at' => Carbon::now()->addHours(2) | |
]); | |
// Call other functions, they're still part of this transaction | |
$this->generateModelsFromUploadedData($user, $request->file('uploaded_file')); | |
DB::commit(); // Tell Laravel this transacion's all good and it can persist to DB | |
return response([ | |
'message' => "User created successfully", | |
'status' => "success" | |
], 200); | |
} catch(\Exception $exp) { | |
DB::rollBack(); // Tell Laravel, "It's not you, it's me. Please don't persist to DB" | |
return response([ | |
'message' => $exp->getMessage(), | |
'status' => 'failed' | |
], 400); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment