Tuesday, 09 Apr, 2024 -254

How to Use Laravel Middleware to Protect Your Application

Laravel  Middleware

Between a request and a response, middleware acts as a link. It is a type of filtering mechanism. This lesson explains  the middleware mechanism in Laravel.

Laravel verifies  user and application authentication if the user is authenticated redirect  successfully  otherwise if not authenticate then not redirect.


*Middleware Create Command :


php artisan make:middleware <middleware-name>

<middleware-name> Here write you middleware name 

After creating middleware you will find it at  app/Http/Middleware directory.

Example :


Following the example and understand the tutorial middleware mechanism

Step 1 : We create admin middleware , let us know our middleware create command 

Php artisan make:middleware adminMiddleware.

Step 2 :after create middleware successfully , you will receive following output 

 

Step 3 : AdminMiddleware will be created at app/Http/Middleware. The newly created file will have the following code already created for you.

<?php


namespace App\Http\Middleware;

use Closure;


class AdminMiddleware {

   public function handle($request, Closure $next) {

      return $next($request);

   }

}


Middleware Registering

  The following is the code for app/Http/Kernel.php

<?php


namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;


class Kernel extends HttpKernel {

   protected $middleware = [

      \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

      \App\Http\Middleware\EncryptCookies::class,

      \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,

      \Illuminate\Session\Middleware\StartSession::class,

      \Illuminate\View\Middleware\ShareErrorsFromSession::class,

      \App\Http\Middleware\VerifyCsrfToken::class,

   ];

  

   protected $routeMiddleware = [

      'auth' => \App\Http\Middleware\Authenticate::class,

      'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,

      'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

      Admin=> \App\Http\Middleware\AdminMiddleware::class,

   ];

}


Step 4: Declare middleware 

Route::get('/', function () {

    //

})->middleware('web');

 

Route::middleware(['web'])->group(function () {

    //

});


Tags
Most Popular
img
02 Apr, 2024 view: 2170
img
02 Apr, 2024 view: 1029
img
01 Apr, 2024 view: 807
img
01 Nov, 2023 view: 748
img
02 Apr, 2024 view: 481
img
26 Apr, 2024 view: 477
img
01 Apr, 2024 view: 327
img
09 Apr, 2024 view: 252
img
18 Apr, 2024 view: 243
img
16 Mar, 2025 view: 28
Trending