Skip to content

Instantly share code, notes, and snippets.

@EricMcWinNer
Created November 28, 2021 22:53
Show Gist options
  • Save EricMcWinNer/3888929ba40e2a3f6fc0c289951c5d36 to your computer and use it in GitHub Desktop.
Save EricMcWinNer/3888929ba40e2a3f6fc0c289951c5d36 to your computer and use it in GitHub Desktop.
Simple Code using laravel transactions closure in DB facade
<?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) {
DB::transaction(function() {
$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)
]);
return response([
'message' => "User created successfully",
'status' => "success"
], 200);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment