How To

What is Middleware and How Does its Functionality Work in Laravel 8?

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!

Click to rate this post!
[Total: 7 Average: 4]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer ? with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket ?.

Recent Posts

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

7 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

1 day ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

1 day ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

2 weeks ago