What is middleware in laravel?

后端 未结 4 1751
野性不改
野性不改 2021-01-19 22:09

I\'m trying to understand how the middleware works in Laravel. Here\'s my class can any one explain how does its works.?



        
4条回答
  •  悲哀的现实
    2021-01-19 22:52

    As you can see what the middleware is, now lets see the code

    public function handle($request, Closure $next)
    {
        if ($request->age <= 200) {
            return redirect('home');
        }
    
        return $next($request);
    }
    

    This code check every request and check the age variable in the request. If the age is less than 200 then the request will be redirect to the home otherwise it will go to the requesting page. Suppose you are requesting /about page but if you can not pass the middleware condition you will be redirected to /home otherwise to /about i.e. given by return $next($request);. Similary works with auth and cors middleware. You can similarly do some check like $request->user->role=='admin' and redirect to admin page or to other page.

    return $next($request); this gives you the next requesting route (the original route that have requested)

提交回复
热议问题