Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save williamjulianvicary/9083663e45444f7670da65b96f37e1a5 to your computer and use it in GitHub Desktop.
Save williamjulianvicary/9083663e45444f7670da65b96f37e1a5 to your computer and use it in GitHub Desktop.
Laravel 5 Middleware for Database Transactions
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
class DBTransaction
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
* @throws \Exception
*/
public function handle($request, Closure $next)
{
\DB::beginTransaction();
try {
$response = $next($request);
} catch (\Exception $e) {
\DB::rollBack();
throw $e;
}
if ($response instanceof Response && $response->getStatusCode() > 399) {
\DB::rollBack();
} else {
\DB::commit();
}
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment