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.
Contents
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.
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.
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); } }
We need to register every middleware before using it. There are two types of 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, ];
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 ];
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']);
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!
Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…
In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…
October was an exciting month for MageComp! From significant updates across our Magento 2 extension…
In modern web development, seamless navigation and state management are crucial for delivering a smooth…
Magento Open Source 2.4.8 beta version released on October 8, 2024. The latest release of…
Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…