Laravel 5.5 Middleware Complete Tutorial

devquora
devquora

Posted On: Jan 31, 2023

Laravel 5.5 Middleware Complete Tutorial

 

Hope you are doing great. You are here because you want to explore new possibilities to create robust and scalable PHP application using Laravel Framework. In this tutorial, we are going to cover topic's like

What are middlewares in Laravel

In Laravel, you can think middleware as a system or tool that are used to filter all HTTP requests entering your application. Middleware works between request and response of our application. It sits between Request and Response like a firewall that examine whether to route a request. Laravel comes with several inbuilt middlewares like EncryptCookies , RedirectIfAuthenticated, trim strings, TrustProxies etc. All middlewares are located in the app/Http/Middleware directory of  Laravel App.

Types of middlewares in Laravel?

There are three types of middleware are available in Laravel.

How to use middleware in Laravel 5

Global Middleware: They run on every HTTP request of the application.Can be assigned in "$middleware" array of Kernel class which is located at app/Http/Kernel.php.

 /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\YourMiddleare::class,
    ];
Route Middleware groups: They run on specific route groups of application and can be assigned by listing your middleware class in "$middlewareGroups" array of Kernel class which is located at app/Http/Kernel.php.
   /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\YourMiddleare::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
Route Middleware: They run on a specific route of application.To assign route middleware on specific routes, you should first assign your middleware a key with class in "$routeMiddleware" array of your app/Http/Kernel.php file.
   /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
	'YourMiddleare' => \App\Http\Middleware\YourMiddleare::class,
    ];
Once the middleware has been assigned in $routeMiddleware array of the HTTP kernel, you may use the middleware method to assign middleware to a route:
Route::get('admin/profile', function () {
    //
})->middleware('auth');

How to create custom middleware in Laravel 5.5?

As we have understood the basics of Middleware in Laravel now its time to create a custom Middleware in Laravel. In this post, we are going to create a custom middleware in Laravel to redirect a visitor to a country subdomain based on location, if the visitor is not coming from the US. Many of e-commerce website do such type of task to personalized user experience based on their location.This middleware is helpful to do so. Lets started, follow the steps with me I am assuming you have already installed Laravel 5.5 on your server, if not please click here to install and configure Laravel 5.5

Step 1: Creating our middleware:

In Laravel you create a new middleware, using the make:middleware Artisan command:
php artisan make:middleware locationRedirect
Above command will a new php file named locationRedirect.php in app/Http/Middleware directory. Open your locationRedirect.php file and put below code in that.
<?php
namespace App\Http\Middleware;
use Closure;
use Request;
class locationRedirect
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
       // getting user country based on ip address
        $ip= $request->ip();
        $user_country_code="us";
        $ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
        if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
             $user_country_code= @$ipdat->geoplugin_countryCode;
         }
         if($user_country_code!=null &&  $user_country_code !="us"){
           $user_domain=$user_country_code."yourdomain.com";
           return Redirect::to($user_domain);
         }
        return $next($request);
    }
}

?>

Now we need to register and create aliases for our middleware in Kernel.php file so please open app/Http/Kernel.php and add our middleware in the $routeMiddleware array.
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
	
     /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
      // \App\Http\Middleware\locationRedirect::class, // uncomment for global usage
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
	'locationRedirect' => \App\Http\Middleware\locationRedirect::class, // for specific route
    ];
}
?>

Now our custom Middleware locationRedirect is configured and ready to use in our app for specific routes. If you want to use this middleware globally then please uncomment " // \App\Http\Middleware\locationRedirect::class, // uncomment for global usage" line from $middleware array of app/Http/Kernel.php. For specific route do as below.
Route::get('/', function () {
    //
})->middleware('locationRedirect');

Also Read Top laravel interview questions and answers

Thanks for reading.

Please let me know if article helps you or if you have any doubts and suggestion please post a comment!

    Please Login or Register to leave a response.

    Related Articles

    Laravel Tutorials

    Laravel Pagination Ajax

    Creating Ajax based pagination is Laravel 5.6. Ajax (Asynchronous JavaScript and XML) is a technique to update a specific part of webpage asynchronously without reloading the page. In this article, we..

    Laravel Tutorials

    Laravel Pagination

    According to Wikipedia Pagination is a process of separating or dividing a document or digital contents into discrete pages. In Core PHP and other frameworks, paginating record is a painful task. Lara..

    Laravel Tutorials

    Configuring Errors & Logging in Laravel 5

    Laravel comes with excellent error and exception handling feature. When you install Laravel framework (MVC) error and exception handling is configured at the same time. In this tutorial, we will see h..