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: 6 Average: 4.5]
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

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

5 hours ago

Optimizing Laravel Blade: Unlocking Advanced Fetcher Techniques

In the expansive universe of Laravel development, Blade serves as the stellar templating engine, propelling…

7 hours ago

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

2 days ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

5 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

1 week ago

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

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

1 week ago