Concept of Middleware in Laravel Tutorial

Middleware is one other important part of Laravel and offers the method to filter HTTP requests that get entered into your project. Let us assume a scenario the place this middleware of Laravel checks for an authenticated user of your software program or project. In case the authentication is verified as valid, the middleware characteristic will let the user proceed along with your project. There is one other middleware title CORS, that’s in control of including appropriate headers to all of your responses.

Define Middleware

Middleware will be defined as a middle-man or interface acting in coordination between a request and a response. As talked about within the above take a look at scenario, if the user isn’t authenticated, then your project might redirect that user from login.php to index.php web page.

You can create your middleware by working the syntax mentioned below:Syntax:

php artisan make:middleware<middleware_name>

Here, you need to replace the <middleware_name> along with our middleware. You can see this path location app/Http/Middleware the middleware that you can be creating your project.

php artisan make:middleware AgeUser

Register Middleware

Before using any middleware, you need to register it.Laravel offers two kinds of Middlewares. These are:

  • Global Middleware
  • Route Middleware

Global middlewares are people who shall be running during each HTTP request of our application. In the $middleware property of your app/Http/Kernel.php class, we may list all the worldwide middleware on your project.

When you desire a middleware to particular routes, you need to add the middleware with a key on our app/Http/Kernel.php file, and such middlewares are known as route middleware. $routeMiddleware, by default, holds entries for the middleware which can be already included in Laravel. For including your customized middleware, it’s worthwhile to append them to the list and add a key of your choice.

protected $routeMiddleware = [
   'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
   'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
   'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
   'userAuth' => \Illuminate\Routing\Middleware\UserAuthRequests::class,
];

Parameters of Middleware

Parameters may also be handed to middlewares. Various parameterized conditions will be one thing when our project has attributes like a customer, employee, admin, owner, and so forth. and also you need to execute totally different modules primarily based on the roles of the user, for these conditions, parameters of middlewares turns into helpful.

public function handle($request, Closure $next, $profile)
   {
       if (! $request->user()->hasProfile($profile)) {
           // Next page
       }
       return $next($request);
   }
}

You have to create the Profile middleware by working the code talked about below:

php artisan make:middleware ProfileMiddleware

The newly created middleware will be dealt with using the code: app/Http/Middleware/ProfileMiddleware.php

<?php

namespace App\Http\Middleware;
use Closure;

class ProfileMiddleware {
   public function handle($request, Closure $next, $Profile) {
      echo "Role: ".$Profile;
      return $next($request);
   }
}

Register the ProfileMiddleware in appHttpKernel.php file. Add the road highlighted in that file to register ProfileMiddleware.

protected $routeMiddleware = [
   'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
   'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
   'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
   'userAuth' => \Illuminate\Routing\Middleware\UserAuthRequests::class,
   'Age' => \App\Http\Middleware\AgeMiddleware::class,
   'Profile' => \App\Http\Middleware\ProfileMiddleware::class,
];

Terminate Middleware

These are particular kinds of middlewares that begin working proper after any response is sent to the browser. The terminate methodology is used for attaining this. When a terminate methodology is used within the middleware of your project, it will get known as automatically after the browser response is sent.

Create TerminateMiddleware by executing the under command.

php artisan make:middleware TerminateMiddleware

Copy the next code within the newly created TerminateMiddleware at app/Http/Middleware/TerminateMiddleware.php.

<?php

namespace Illuminate\Session\Middleware;
use Closure;
class TerminateMiddleware
{
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
    public function terminate($request, $response)
    {
        // tasks assigned within terminate method
    }
}

Register the TerminateMiddleware in appHttpKernel.php file. Add the line highlighted in color in that file to register TerminateMiddleware.

protected $routeMiddleware = [
   'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
   'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
   'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
   'userAuth' => \Illuminate\Routing\Middleware\UserAuthRequests::class,
   'Age' => \App\Http\Middleware\AgeMiddleware::class,
   'Profile' => \App\Http\Middleware\ProfileMiddleware::class,
   'Terminate' => \App\Http\Middleware\TerminateMiddleware::class,
];

Attaching a Middleware to a Route

Take this route for example,

Route::get('posts/{something}', 'PostController@getPost');

the getPost method on the PostController class fires when the URL matches posts/{something}.

We could add our down.for.maintenance middleware by changing the second parameter of Route::get to an array which contains a middleware property and closure which processes the route.

Route::get('posts/{something}', ['middleware' => 'grown.ups.only', function () {
    return "Only big boys/girls can see this.";
}]);

By doing this, only routes matching posts/{something} will show doing something error.

Another to add middleware to routes is to call a middleware method on the route definition. Like this.

Route::get('posts/{something}', function () {
    //
})->middleware(['first', 'second']);

<— Previous Tutorial Next Tutorial —>

LEAVE A REPLY

Please enter your comment!
Please enter your name here

564FansLike

Related Articles

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.
WP2Social Auto Publish Powered By : XYZScripts.com