laravelclosuresmiddleware

What does 'return $next($request)' do in Laravel middleware?


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.


Solution

  • $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.