Hello Laravel Friends,
In this Laravel tutorial, we will learn about Middleware in Laravel 8 with an example. First, let’s start by understanding the meaning of middleware in Laravel.
What is Middleware in Laravel?
Middleware is a type of filtering mechanism for HTTP requests in Laravel. It acts as an intermediary between the user request and response.
For example, Laravel middleware verifies whether your application’s user is authenticated or not. If the user is not authenticated, the middleware will redirect the user to your application’s login screen. However, if the user is authenticated, the middleware will allow the request to move further into the application.
Create Middleware
Use the below command to create middleware.
php artisan make:middleware <middleware-name>
The file will be created in this path app/Http/Middleware directory.
Create UserAuthenticated Middleware
Run the below command to create UserAuthenticated middleware
php artisan make:middleware UserAuthenticated
Now add your logic
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Session; class UserAuthenticated { /** * 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::guard('web')->guest()) { if ($request->ajax() || $request->wantsJson()) { return response([ "status" => 0, "data" => "You are not login" ],200); } else { Session::put('error', 'You are not login.'); return redirect()->route('customerHome'); } } return $next($request); } }
Registering Middleware
We need to register every middleware before using it. There are two types of middleware.
1. Global Middleware
Global middlewares are those that will be running during every HTTP request of your application. In the $middleware property of your app/Http/Kernel.php class, you can list all the global middleware for your project.
// Within App\Http\Kernel Class... /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array<int, class-string|string> */ protected $middleware = [ // \App\Http\Middleware\TrustHosts::class, \App\Http\Middleware\TrustProxies::class, \Fruitcake\Cors\HandleCors::class, \App\Http\Middleware\PreventRequestsDuringMaintenance::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, ];
2. Route Middlewares
If you would like to assign middleware to specific routes, you should first assign the middleware a key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. You may add your own middleware to this list and assign it a key of your choice.
// Within App\Http\Kernel Class... protected $routeMiddleware = [ 'userauth' => \App\Http\Middleware\UserAuthenticated::class, 'auth' => \App\Http\Middleware\Authenticate::class, 'adminauth' => \App\Http\Middleware\AdminAuthenticated::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 'isAdminVerified' => \App\Http\Middleware\IsAdminVerifiedMiddleware::class, 'kycVerified' => \App\Http\Middleware\KycVerifiedMiddleware::class, 'kycDetails' => \App\Http\Middleware\KycDetailsMiddleware::class ];
Assign Middleware to Route
After defining the middleware in the HTTP kernel, you can use the middleware method to assign middleware to a route.
Route::get('/test', function () { // })->middleware('userauth');
Also, you assign multiple middlewares to the route.
Route::get('/test', function () { // })->middleware(['first', 'second']);
Conclusion:
This was all about middleware in Laravel 8. If you have any doubts, you can connect with our Laravel developers, who will help you provide solutions for your difficulties. Stay in touch with us for more Laravel tutorials.
Happy Coding!