Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is middleware in laravel?

Tags:

php

laravel

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

<?php

namespace App\Http\Middleware;

use Closure;

class CheckAge
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->age <= 200) {
            return redirect('home');
        }

        return $next($request);
    }

}

Thanks

like image 717
Ajay Korat Avatar asked Dec 23 '22 19:12

Ajay Korat


1 Answers

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Reference

Edit: As explained by @num8er

Middleware is the function (or logic) that stands between router and route handler.

In your code:

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

    return $next($request);
}

$request->age is a variable that provided in request and can be checked on each HTTP request, if its value <= 200 then user redirects to home route.

like image 118
Mayank Pandeyz Avatar answered Dec 26 '22 17:12

Mayank Pandeyz