Please respect that I'm new to programming and Laravel, so this question might seem a little odd to the most of you.
But I think this is what stackoverflow is for, so:
When I created a new middleware with the command php artisan make:middleware setLocale
there was already the handle
-function with this code in it:
return $next($request);
and I'm wondering what exactly this line does.
A Closure is an anonymous function. Closures are often used as callback methods and can be used as a parameter in a function. If you take the following example: function handle(Closure $closure) { $closure(); } handle(function(){ echo 'Hello! '; });
Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated.
The handle method is invoked when the job is processed by the queue. Note that we are able to type-hint dependencies on the handle method of the job. The Laravel service container automatically injects these dependencies.
A middleware which checks if the current user is logged in and stops them seeing guest pages such as login. If you are logged in then it makes no sense to be able to view the login view, the user gets redirected to the dashboard instead.
$next($request)
just passes the request to next handler.
Suppose you added a middleware for checking age limit.
public function handle($request, Closure $next)
{
if ($request->age <= 18) {
return redirect('home');
}
return $next($request);
}
when age is less than 18 it will redirect to home but when the request passes the condition what should be done with the request? it will pass it to next handler.Probably to the register user method or any view.
This is explained in the documentation:
To pass the request deeper into the application (allowing the middleware to "pass"), call the $next callback with the $request.
It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.
https://laravel.com/docs/5.8/middleware#defining-middleware
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With