Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 609
ofmiceandmoon Avatar asked Apr 25 '19 14:04

ofmiceandmoon


People also ask

What is Closure $Next in Laravel?

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! '; });

What does middleware do in Laravel?

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.

What is handle function in Laravel?

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.

What is guest middleware in Laravel?

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.


2 Answers

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

like image 144
Yasir Avatar answered Oct 01 '22 12:10

Yasir


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

like image 29
Christian C Avatar answered Oct 01 '22 11:10

Christian C