How to Create Custom Middleware in Laravel?

How to Create Custom Middleware in Laravel?

In this Laravel middleware tutorial, we will learn how to create custom middleware and how it use in laravel based projects. Simply create one custom middleware and check the language in the query string.
And this example also works with Laravel version.

Simply Laravel middleware filter all the HTTP request in Laravel based projects. For example when the user is do any request that time middleware checks user is logged in or not and redirected accordingly. Any user is not logged in but she/he wants to access the dashboard or other things in projects that time middleware filter request redirect to the user.

How to Create Custom Middleware in Laravel?

Using the below-given steps, you can create and use custom middleware in laravel applications:

Create Middleware

In this step, We have to create custom middleware in laravel 5.7 based project. So let’s open your command prompt and run below command :

php artisan make:middleware CheckLang

After successfully create middleware, go to app/http/kernel.php and register your custom middleware here :

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 = [
        ....
        'checkLang' => \App\Http\Middleware\CheckLang::class,
    ];
}

After successfully registering your middleware in Laravel project, go to app/HTTP/middleware and implement your logic here :

app/Http/Middleware/CheckLang.php

<?php

namespace App\Http\Middleware;

use Closure;

class CheckLang
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->lang == 'en' || $request->lang == 'ar') {
            return $next($request);
        }
            return response()->json('Not Allow');

    }
}

Add Route

In this step, simply we will create a route and use custom middleware here. Filter http every request and protect routes :

 
//routes/web.php

Route::middleware(['checkLang'])->group(function(){

Route::get('validate', 'HomeController@validate');

});

Add Method in Controller

Now we will create one method name language and let’s check :

app/Http/Controllers/HomeController.php

<?php

 namespace App\Http\Controllers;

 use Illuminate\Http\Request;
 class HomeController extends Controller
 {
     public function validate()
     {
         dd('Allow');
     }
 }

Start Development Server

We need to start the development server. Use the php artisan serve command and start your server :

 php artisan serve
If you want to run the project diffrent port so use this below command
php artisan serve --port=8080

Now hit the below route in the browser :

http://localhost:8000/validate?lang='en'

We will pass lang=”en” or lang=”ar” in the query string, our created custom middleware checked, if exist en or ar in the query string that time it will redirect to the controller method otherwise it display “Not Allow” message

Conclusion

In this Laravel tutorial for custom middleware, We have successfully created custom middleware in laravel based projects with simple examples. our examples run quickly.

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.

Leave a Reply

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