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.

Whenever there is request by a user then request has to go first on the middleware and when middleware authorized that request then it will go to the backend.

Defining Middleware

cd DirectoryName
php artisan make:middleware MiddlewareName

after creating middleware


namespace App\Http\Middleware;

use Closure;

class test
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
    public function handle($request, Closure $next)
        $ip = $request->ip();
        if($ip == ''){
            throw new \Exception("your IP is correct");            
            //return redirect('/');
        return $next($request);

Assigning Middleware To Routes:

Route::get('about', function () {
    return view('about');

Registering Middleware

If you want a middleware to run during every HTTP request to your application, you should first assign the middleware a key in your app/Http/Kernel.php file.

protected $routeMiddleware = [    
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'test' => \App\Http\Middleware\test::class,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s