How Middleware works in Laravel 5.7

One of the nice feature of Laravel is  it’s Middleware. In this post we will learn the basics of Laravel 5.7 Middleware. Once you will understand the basics of Middleware you can explore in details at your end. In next posts I will go through Middleware in details. But in this post I will  make you understand the middleware term in a simple way.

What is Middleware: 

  • As the name proposes, Middleware in Laravel sits in between a HTTP Request & Response.
  • It provides a convenient mechanism for filtering HTTP requests entering your application.
  • So It’s a filtering mechanism which filters the incoming HTTP request.
  • It works as a middleman between Request and Response like a firewall to examine whether to route a request.

Example of a Middleware:

A middleware in Laravel, which verifies whether the user of the application are authenticated user or not. If the user is authenticated one, then the user will be redirected to Dashboard page /Main page/ Any custom page. And if the user found to be unauthenticated , then that user will redirect to the login Page.

All middlewares in Laravel 5.7 are located in the app/Http/Middleware directory as shown below.

 

As per your requirement you can write middlewares to perform a variety of tasks in your application. But In Laravel 5.7 there are some inbuilt  Middlewares with which you can work. All these middlewares are located in the above mentioned path.

Some of the inbuilt middlewares in laravel 5.7 are  Authenticate , CheckForMaintenanceMode, EncryptCookies , RedirectIfAuthenticated, TrimStrings, TrustProxies , VerifyCsrfToken etc.

Following is a brief intro of these Middlewares.

  • Authenticate Middleware: The user should be redirected to when they are not authenticated.

File path: app/Http/Middleware/Authenticate.php

  • Check For Maintenance Mode Middleware: The URIs should be reachable while maintenance mode is enabled.

File  path: app/Http/Middleware/CheckForMaintenanceMode.php

  • EncryptCookies Middleware: This Middleware will check for encrypt cookies.

File  path: app/Http/Middleware/EncryptCookies.php

  • Redirect If Authenticated Middleware: This Middleware will handle incoming requests. If request is authenticated it will redirect.

File  path: app/Http/Middleware/RedirectIfAuthenticated.php

  • TrimStrings : This middleware will trim strings.

File  path: app/Http/Middleware/TrimStrings.php

  • TrustProxies : Trusted Proxy tells Laravel about proxies that can be trusted. This middleware will detect proxies in the application.

File  path: app/Http/Middleware/TrustProxies.php

Let’s explore how to define Middleware.

Defining Middleware

Creating middlewares in Laravel is easy. To create/define a new Middleware use the following artisan command


php artisan make:middleware Middlewarename 

Replace Middlewarename with the actual name of the middleware.

php artisan make:middleware FindRating


Now you can see a new FindRating.php file placed within your app/Http/Middleware directory.

The default code in a new middleware is as follows.



<?php
namespace App\Http\Middleware;

use Closure;

class FindRating
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}

 

In this middleware, we will only allow access to the route if the supplied Rating is greater than 4. Otherwise, we will redirect the users back to the home URI:

So we will modify our  middleware code .



if($rating >= 4) {
            return redirect('home');
        }
        return $next($request);
    }
}

As you can see, if the given rating is greater than or equal to 4, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to “pass”), call the $next callback with the $request.

Before & After Middleware

Whether a middleware runs before or after a request depends on the middleware itself. For example, the following middleware would perform some task before the request is handled by the application:


<?php

namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware
{
    public function handle($request, Closure $next)
    {
        // Perform action

        return $next($request);
    }
}

However, this middleware would perform its task after the request is handled by the application:


<?php

namespace App\Http\Middleware;

use Closure;

class AfterMiddleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // Perform action

        return $response;
    }
}

Registering Middleware

If you want a middleware to run on every http request to your application, go to app/Http/kernel.php and add the middleware FQN to Kernel class $middleware property.



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

You can see the above middlewares added to $routeMiddleware property.
To add your own middleware append it to the above list & assign it a key. in above code auth,auth.basic,bindings & can etc are key.

Once the middleware has been defined in the HTTP kernel, you may use the middleware method to assign middleware to a route:



Route::get('user/profile', function () {
    //
})->middleware('auth');

When assigning middleware, you may also pass the fully class name:



use App\Http\Middleware\CheckAge;

Route::get('user/profile', function () {
    //
})->middleware(FindRating::class);

Middleware Groups

You can define middleware groups in app\Http\Kernel.php. There’s a property named $middlewareGroups. In thi an multidimensional array, you can see each key is a name and each value is the corresponding middleware.

The default middleware group in laravel are web & api which contain common middleware you can apply in your appplication.



 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,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware. Also middleware groups make it more convenient to


  Route::get('/', function () { 
   })->middleware('web');

Route::group(['middleware' => ['web']], function () {
    //
});assign many middleware to a route at once:


This all are the basics of Middleware. Once you understand the basics you can explore Middleware in details.

Have fun working with Laravel Basic Middleware !!

Leave a reply:

Your email address will not be published.

Site Footer