I'm reading the Laravel documentation on Middleware, specifically the part that talks about after and before . I don't understand the concept. It seems that the Middleware before is executed when the request arrives, and it depends on it whether or not the request continues to the controller. So far, it's clear.
However, I don't see the after thing clearly. I think I understand that first the request is passed to the controller and then the middleware is executed. However, I've tested it and it doesn't seem to work like that. I have used a Middleware that filters based on the value of a data, as a test:
public function handle($request, Closure $next)
{
$response = $next($request);
$id = $request->route('id');
if ($id < 30) {
dd("El id no es válido");
}
return $response;
}
The point is that with this code, whatever the value of id
is passed directly to the controller, and the Middleware does nothing, nor does it show anything, neither before nor after.
What I ask is that someone clarify the concept for me and show me an example that illustrates it, that I can reproduce and execute, to understand after.
For example, you have middleware
BeforeMiddleware
that checks if the{id}
route parameter is less than 30, and if so, redirects to the viewwelcome
with a flash session message indicating that it was redirected by this middleware. Otherwise, it continues with the execution of the application:Also, you have a middleware
AfterMiddleware
that checks if the{id}
route parameter is less than 40, and if so, it redirects the viewwelcome
with a flash session message indicating that it was redirected by this other middleware:You have these two routes, each returning a different view. To the route that expects the parameter
{id}
, you apply both middlewares:web.php
The views are very simple. Only that in the view
welcome
, the session value that is set in the middlewares is shown:welcome.blade.php
valid_id.blade.php
With that you can test it.
If you enter, for example, localhost:8000/21 , it will not pass the
BeforeMiddleware
(21 is less than 30), so you will be redirected to the routewelcome
, which in the returned view will show you the following message:If you enter localhost:8000/31 , it will pass the
BeforeMiddleware
(31 is not less than 30), but it will not pass theAfterMiddleware
(31 is less than 40), so you will be redirected to the routewelcome
, which in the view will show you the following message:Finally, if you enter localhost:8000/41 , it will pass the
BeforeMiddleware
(41 is not less than 30), and it will also pass theAfterMiddleware
(41 is not less than 40), so it will return the viewid_valido.blade.php
: