Authenticate Routes In Laravel 8 Using Middleware

In this tutorial, we will learn about Middleware and how to authenticate routes in Laravel 8 using Middleware.

What is Middleware

How to assign a Middleware to a specific route

Before assigning a Middleware for a particular route, we have to provide a class for that Middleware with the help of a key.

By default Laravel has provided all the required classes of Middleware in $routeMiddleware property inside App\Http\Kernal.php. as shown below

protected $routeMiddleware = [

'auth' => \Illuminate\Auth\Middleware\Authenticate::class,

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

'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,

'can' => \Illuminate\Auth\Middleware\Authorize::class,

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

'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

'auth.jwt' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class,

];

Now, we can assign the Middleware for a specific route. Below is an example of Middleware for user authentication.

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

//

})->middleware('auth');

Also Read, CRUD operation in laravel 5.8 step by step for Beginners

Assign Middleware groups to multiple routes

However, if we want to assign Middleware to multiple routes at once then we can do this by assigning middleware groups.

There are two Middleware groups provided by Laravel App\Providers\RouteServiceProvider.

We can find these two groups inside the App\Http\Kernel.php

protected $middlewareGroups = [

'web' => [

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

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

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

// \Illuminate\Session\Middleware\AuthenticateSession::class,

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

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

\Illuminate\Routing\Middleware\SubstituteBindings::class,

],

'api' => [

'throttle:api',

\Illuminate\Routing\Middleware\SubstituteBindings::class,

],

];

We can use the above Middlewares as shown below-

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

//

Here you can define all the routes

});

Now, all the routes of your application are protected.

Also Read, How to create laravel project from scratch step by step

Conclusion:- I hope this tutorial will help you to Authenticate routes in Laravel 8 using middleware.

Hi, This is Biplab and I am web developer well versed in PHP and other open source technologies. I am here to share my experience with the community.