Skip to content

Instantly share code, notes, and snippets.

@jalallinux
Created September 13, 2023 08:45
Show Gist options
  • Save jalallinux/c706c17db9b96d0fd5bfd59bdd7594c1 to your computer and use it in GitHub Desktop.
Save jalallinux/c706c17db9b96d0fd5bfd59bdd7594c1 to your computer and use it in GitHub Desktop.
CanFail middleware to handle Database Transaction on whole request
<?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