Table of Contents
Introduction:
Authentication middleware in Laravel is used to authenticate users before they can access certain parts of your application. This is done by checking whether the user is logged in and has the necessary permissions to access the requested resource. In this tutorial, we will show you how to create an authentication middleware and use it to protect routes in your application.
Create a new middleware
First, you need to create a new middleware using the following command:
php artisan make:middleware AuthMiddleware
This will create a new middleware class in the app/Http/Middleware directory.
Define the authentication logic
In the handle method of the middleware class, you can define the logic that checks if the user is authenticated and has the necessary permissions. For example, you can use the Auth facade to check if the user is logged in and redirect them to the login page if they are not:
use Illuminate\Support\Facades\Auth;
public function handle($request, Closure $next)
{
if (Auth::check()) {
return $next($request);
}
return redirect('login');
}
Register the middleware:
Next, you need to register the middleware in the app/Http/Kernel.php file. You can register it as a global middleware or a route middleware depending on your needs.
Apply the middleware:
Finally, you can apply the middleware to the routes or controllers that need it. For example, if you want to protect the profile page and require users to be logged in to view it, you can use the middleware method on the Route facade:
Route::middleware(AuthMiddleware::class)->group(function () {
Route::get('/profile', [ProfileController::class, 'index']);
});
In this example, the AuthMiddleware will be applied to the profile page route and the authentication logic defined in the middleware will be checked before the request is passed to the controller. If the user is not logged in, they will be redirected to the login page.
You can further customize the middleware by adding more authentication logic such as checking for specific roles or permissions. Laravel has several built-in middlewares that you can use as reference, such as the auth
and auth:api
middleware.
Summary:
It’s important to notice that Laravel also provides a guard system which is a more powerful way to handle the authentication, you can use the guard to define how the authentication will be handled, for example, using the guard you can authenticate the user using their email, or you can authenticate them using their credentials but saving the session in a different way.
This is just a basic example of how you can create an authentication middleware in Laravel. You can customize it to suit your needs by adding more authentication logic, changing the redirects, or adding other functionality.
Must Read: What is middle Middleware and how to use Middleware in Laravel Framework?