Created
September 13, 2023 08:45
-
-
Save jalallinux/c706c17db9b96d0fd5bfd59bdd7594c1 to your computer and use it in GitHub Desktop.
CanFail middleware to handle Database Transaction on whole request
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\Http\Middleware; | |
use Closure; | |
use Illuminate\Http\Request; | |
use Illuminate\Support\Facades\DB; | |
use Symfony\Component\HttpFoundation\Response; | |
class CanFailMiddleware | |
{ | |
public function handle(Request $request, Closure $next): Response | |
{ | |
DB::beginTransaction(); | |
try { | |
// Your middleware logic here | |
// For example, interacting with the database | |
// Capture the response before committing | |
$response = $next($request); | |
// Commit the transaction | |
DB::commit(); | |
// Return the captured response | |
return $response; | |
} catch (\Exception $e) { | |
// If an exception occurs, rollback the transaction | |
DB::rollBack(); | |
// Now throw captured exception | |
throw $e; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment