How to Create and Use Custom Middleware in Laravel 10

How to Create and Use Custom Middleware in Laravel 10

If you are working on Laravel 10 web application and you do not know about middleware or you want to know about middleware. How middleware is created and how it is used; In this tutorial, you will learn how to create and use middleware in Laravel 10 app.

Laravel has a series of middleware classes that intercept HTTP requests and responses. Its primary purpose is to modify or filter incoming requests before they reach the application’s routes or to modify outgoing responses before they are sent back to the client. Middleware plays an important role in implementing security, handling authentication, and performing various other tasks that may be performed before or after specific routes are accessed.

How to Create and Use Custom Middleware in Laravel 10

By using these steps, you can create and use middleware in laravel 10 apps:

  • Step 1 – Create Middleware
  • Step 2 – Registering Middleware
  • Step 3 – Implement Logic Into Your Middleware File
  • Step 4 – Use Middleware With Routes
  • Step 5 – Create Controller Method

Step 1 – Create Middleware

In this step, open the terminal or command prompt.

And then execute the following command into it to create custom middleware in Laravel app:

php artisan make:middleware CheckStatus

Step 2 – Registering Middleware

Once you have created middleware by using the above command.

Now, you need to visit the app/http/ directory and open kernel.php. And then register your custom middleware into it: is as follows:

app/Http/Kernel.php

<?php


namespace App\Http;


use Illuminate\Foundation\Http\Kernel as HttpKernel;


class Kernel extends HttpKernel
{
    ....


    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        ....
        'checkStatus' => \App\Http\Middleware\CheckStatus::class,
    ];
}

Step 3 – Implement Logic Into Your Middleware File

Once you have registered your middleware in Laravel apps. Then visit the app/HTTP/middleware directory and open the checkStatus.php file.

Here you can do whatever you want to implement in your middleware. As an example, the logic for checking the user status is implemented below.

<?php

namespace App\Http\Middleware;

use Closure;

class CheckStatus
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (auth()->user()->status == 'active') {
            return $next($request);
        }
            return response()->json('Your account is inactive');

    }
}

Step 4 – Use Middleware With Routes

In this step, Visit your Laravel app routes directory and open web.php file. And use custom middleware with routes to filter every HTTP request:

 use App\Http\Controllers\HomeController;
use App\Http\Middleware\CheckStatus;

Route::middleware([CheckStatus::class])->group(function(){

Route::get('home', [HomeController::class,'home']);

});

Step 5 – Create Controller Method

In this step, create one method name home and add this method to the HomeController.php file, which is placed on app/Http/Controllers/ directory:

<?php
 
 namespace App\Http\Controllers;
 
 use Illuminate\Http\Request;
 class HomeController extends Controller
 {
     public function home()
     {
         dd('You are active');
     }
 }
?>

Conclusion

Laravel 10 middleware example; in this tutorial, You have learned how to create custom middleware in Laravel 10 based project and as well as how to use it.

Recommended Laravel Posts

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

One reply to How to Create and Use Custom Middleware in Laravel 10

  1. Attempt to read property “is_admin” on null

    getting this any specific reason
    i read that because the user is not login we are getting this error but when i apply check for login user then it does not come into condition and skip and just not checking the field is_admin

Leave a Reply

Your email address will not be published. Required fields are marked *