Middleware example with authentication Laravel 9; Laravel authentication middleware manages the thing between a request and a response from the client side. It works as robotics between the request and response. it is a type of filtering mechanism. In this Chapter, I will explain auth middleware mechanism step by step in this tutorial.
Laravel middleware works before reach to the routes and applying given conditions. Laravel includes a middleware that verifies the request. and then it will decide to redirect the user to the home page otherwise the login page. For example, if you make middleware for authentication use check the user comes with the given route URL. The middleware will check and redirect the home page if the user authentication, if not then it will redirect to the login page.
If you want to apply some specific group of the route you want to allow it only when the user is authenticated else. So in this case I will create a routes group and in this group, I will put all my authentication routes, and after that if I will apply authentication middleware to whole route groups.
So in this post, I will teach you how to create auth middleware and user registration, login, and access auth routes after login.
Step 1: Create Project
Create laravel 9 projects using the given suggested below command in your terminal. This will take a little time to create a laravel project in your system. This command default will take the current version of the laravel
composer create-project --prefer-dist laravel/laravel laravel cd laravel
Step 2: Configuration Database
After Successfully creating the laravel project we will config our database. First, I will go to my PHPMyAdmin and create a database.
Then we will put this database name in the .env.If not found the .env file in your root just create and copy form .env.example file and config.
DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=#database_name DB_USERNAME=#database_username DB_PASSWORD=#database__password
Step 3: Create Middleware
Create middleware using the below command in your terminal, In the argument of this command is the name of your middleware file. I have given my middleware name LoginAuthMiddleware.
php artisan make:middleware LoginAuthMiddleware
Goto your middleware, Add just Auth::check() condition in the handle method this middleware. If the user is not authorized then it will redirect to the login form. This is simple logic.
app/Http/Middleware/LoginAuthMiddleware.php<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Auth; class LoginAuthMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse */ public function handle(Request $request, Closure $next) { if (! Auth::check()) { return redirect()->route('login.form'); } return $next($request); } }
Step 4: Register Middleware
Now time to register this middleware in the kernel file. Goto given path. you will find a route middleware protected array variable as below given. Given your middleware path and name this path what name do you want to access this middleware?
REST API Authentication With Laravel Passport - Webappfix
app/Http/Kernel.phpprotected $routeMiddleware = [ 'user.auth.check' => \App\Http\Middleware\LoginAuthMiddleware::class, ];
Step 5: Create Routes
Create a UserLoginController Using the below suggested command in your project terminal. It command will create a controller in your controller folder.
php artisan make:controller UserLoginController
Import UserLoginController And Define routes.
The first route for the user login form. This route will redirect the user to the login form. The second route for the user login form submits and check credential with auth attempt. The third route for the user registration is if there is no account in our database, They can register form and then the fourth routes for the registration form submit.
Create a route group, inside the group pass an array, First is a middleware which we registred in kernel file with the name. Other keys for prefix user apply if you want to give else remove.
routes/web.php<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\UserLoginController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/',[UserLoginController::class,'loginForm'])->name('login.form'); Route::post('login',[UserLoginController::class,'loginAttempt'])->name('login'); Route::get('user/register/form',[UserLoginController::class,'userRegisterForm'])->name('user.register.form'); Route::post('user/register',[UserLoginController::class,'userRegister'])->name('user.register'); Route::group(['middleware' => 'user.auth.check','prefix' => 'user'],function () { Route::get('home',[UserLoginController::class,'home'])->name('home'); Route::get('logout',[UserLoginController::class,'logout'])->name('logout'); });
Step 6: Controller Methods
Define all the methods here in this controller which we create a route in the web.php file.
app/Http/Controllers/UserLoginController.php<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Validator; use Hash; use Auth; class UserLoginController extends Controller { public function userRegisterForm(Request $request) { return view('user-register-form'); } public function userRegister(Request $request) { $this->validate($request,[ 'email' => 'email|required', 'password' => 'required' ]); $request = $request->all(); $request['password'] = bcrypt($request['password']); User::create($request); return redirect()->route('login.form'); } public function loginForm(Request $request) { if (Auth::check()) { return redirect()->route('home'); } return view('user-login'); } public function loginAttempt(Request $request) { $this->validate($request,[ 'email' => 'email|required', 'password' => 'required' ]); if(! Auth::attempt(['email' => $request->email,'password' => $request->password])){ return redirect()->route('login.form'); } return redirect()->route('home'); } public function home() { if (! Auth::check()) { return redirect()->route('login.fomr'); } return view('home'); } public function logout(Request $request) { Auth::logout(); return redirect()->route('login.form'); } }
Step 7: Blade Files
HomePage, If the user will authentication then they will redirect to the homepage.
resources/views/home.blade.php<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>HomePage - Webappfix </title> </head> <body> Hi {{ auth()->user()->name }} <a href="{{ route('logout') }}">Logout</a> </body> </html>
User Login Form, If the user does not authentication then they will redirect to the login form.
resources/views/user-login.blade.php<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Login Form - Webappfix</title> </head> <body> <a href="{{ route('user.register.form') }}">Registration</a> <form action="{{ route('login') }}" method="post"> @csrf <label for=""> Email <input type="text" name="email"> </label> <label for=""> Password <input type="text" name="password"> </label> <input type="submit"> </form> </body> </html>
Registration Form, If the user does not register with the existing system. Create their credential with the registration.
resources/views/user-register-form.blade.php<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>User Register Form - Webappfix</title> </head> <body> <a href="{{ route('login.form') }}">Login</a> <form action="{{ route('user.register') }}" method="post"> @csrf <label> Name : <input type="text" name="name"> </label> <label> Email : <input type="text" name="email"> </label> <label> Password : <input type="text" name="password"> </label> <input type="submit"> </form> </body> </html>
Step 8: Development Server Start
Start your development server using the given command in your terminal. This command starts your application development server.
php artisan server
CONCLUSION
All the steps necessary for user authentication using auth custom-made middleware. This middleware run will that request on which you apply on the routes. Solve your auth middleware problem and make your user authentication in your leave application.
We always thanks to you for reading our blogs.

Dharmesh Chauhan
(Swapinfoway Founder)Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

Haresh Chauhan
(Co-Founder)We Are Also Recommending You :
- How To Restrict User Access From IP Address Laravel
- Laravel JSON Data Search/Filter From Database Example
- could not encode content to iso-8859-1
- Parent OrderBy From Many Child's Laravel Example
- How to get images from outside project directory laravel
- How To Use Where Clause With Two Fields Of The Same Table Examples
- Laravel Remove index.php From URL
- Email Send Using Queue In Laravel
- Laravel 9 Sanctum API Authentication Tutorial
- Laravel 10 Create Controller Example