# Debug middleware
- Middleware is a piece of code that is run between the request and the response.
- Global middleware runs for every HTTP request while route middleware runs only for HTTP requests to specific routes.
- Sometimes it is also useful to write your own middleware that contains functionality you will often use in your application.
E.g: in a controller, you fetch a dataset and then send it to a view. For debugging, it is useful to only show the dataset in JSON format or just dump the data to te screen and stop the execution of the script.
# Preparation
- You only have to do these actions once!
- Create new middleware:
php artisan make:middleware Debug
- Open the file app/Http/Kernel.php and register the middleware in the
middlewareGroups
array under theweb
group
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\Debug::class,
\App\Http\Middleware\EncryptCookies::class,
...
],
'api' => [
...
],
];
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
- Open the file app/Http/Middleware/Debug.php and replace the code inside the
handle
method with the code below:
public function handle(Request $request, Closure $next)
{
// set $onlyInDebugMode to false if this method is also allowed to work on the production server
$onlyInDebugMode = true;
$response = $next($request);
// go to the view if $onlyInDebugMode = true and if APP_DEBUG = false in .env file
if ($onlyInDebugMode && !config('app.debug')) {
return $response;
}
if ($request->hasAny(['json', 'dd', 'ddd', 'dump']) && $request->getMethod() === 'GET') {
// get the data
$data = $response->getOriginalContent()->getData();
// ?json: output the data as a JSON
if ($request->exists('json') && $request->isNotFilled('json')) return response()->json($data);
// ?dd: dump and die
if ($request->exists('dd') && $request->isNotFilled('dd')) dd($data);
// ?ddd dump, die and debug
if ($request->exists('ddd') && $request->isNotFilled('ddd')) ddd($data);
// ?dump: dump the data and proceed
if ($request->exists('dump') && $request->isNotFilled('dump')) dump($data);
}
return $response;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Usage
REMARKS
- You don't have to create a route or a view right now, just look at how the helper works.
- Tip: download JSON Viewer Pro for Chrome (opens new window) to make JSON easy to read