-
-
Save williamjulianvicary/9083663e45444f7670da65b96f37e1a5 to your computer and use it in GitHub Desktop.
Laravel 5 Middleware for Database Transactions
This file contains 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\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