Home >> Laravel 8.X >> What is Middleware in Laravel 8.X

What is Middleware in Laravel 8.X

Middleware used for filtering HTTP requests of your application. 

Example

Laravel middleware that verifies the user of your application is authenticated or not.
If the user is not authenticated, the middleware will redirect the user to the login screen. 

Laravel middleware such as authentication and CSRF protection, and all these are located in the app/Http/Middleware directory.

Create Middleware

To create a new middleware, use the make:middleware Artisan command.

php artisan make:middleware "name of the middleware"

php artisan make:middleware Checkuser

Example

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class Checkuser{
    
    public function handle($request, Closure $next) {
        
        if(Auth::check() && Auth::user()->user_type == 1){
            return $next($request);
        }
        else{
            return redirect('/sign-in');
        }
    }
}

Apply Middleware
 
Step 1:-
The middleware can be apply at app/Http/Kernel.php.
 /**
  * The application's route middleware.
  *
  * These middleware may be assigned to groups or used individually.
  *
  * @var array
  */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'checkuser' => \App\Http\Middleware\Checkuser::class,
    ];
 
Step 2:- Use command 
 
composer dump-autoload
 
Step 3:- Add the middleware code in the web.php file.

Route::get('/welcome', function () {
    return view('welcome');
});

Route::group(['middleware' => 'checkuser', 'roles' => ['User']], function () {
    
     Route::get('/dashboard', 'UserController@dashboard');
});

Post Your Comment

Next Questions

Copyright ©2022 coderraj.com. All Rights Reserved.