Tutorialsplane

Laravel Middleware


Laravel Middleware – The Laravel Middleware is used to includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen.


Laravel Middleware.

Let us understand how to use laravel Middleware.

Function:-

There are some followings function available in laravel Middleware.

1. Introduction.

Middleware provide a simple mechanism for filtering HTTP requests entering your application. Like Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. Still, if the user is authenticated, the middleware will allow the request to proceed further into the application.

There are several middleware included in the Laravel framework, including middleware for authentication and CSRF protection. All of these middleware are located in the app/http/Middleware directory.

2. Defining Middleware.

To create a new middleware, use the make::middleware Artisan command.

php artisan make:middleware Test1Middleware

This command will place a new Test1Middleware class in your app/Http/middleware directory. In this middleware, we will only allow access to the route.

Middleware Directory Path.

Let’s look at a simple example.

<?php namespace App\Http\Middleware;
use Closure;

class Test1Middleware
{
public function handle($request, Closure $next)
    {
		echo "I Was Called First";
        return $next($request);
    }
}
</pre?>

The middleware can be registered at app/Http/kernel.php.

Kernel path [app/Http/kernel.php].

 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,
     'test' => \App\Http\Middleware\Test1Middleware::class,
     'check' => \App\Http\Middleware\CheckAge::class,
    ];

Controller part:-

<?php namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class MyTestController extends Controller
{
	public function index(){		
        echo "Welcome!!";
	}
}
</pre?>

Route part:-

Route::get('test',[
   'middleware' => 'test',
   'uses' => 'MyTestController@index',
]);

Output will be like this:-

CheckAge

Create a new middleware through command:-

php artisan make:middleware CheckAge

Middleware CheckAge Example

<?php namespace App\Http\Middleware;
use Closure;

class CheckAge
{
public function handle($request, Closure $next)
    {		
        if ($request-?>age <= 200) {
	echo "My age is ";
	echo $request->age;
        }
        return $next($request);
    }
}

Output will be like this:-

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 CheckAge
{
public function handle($request, Closure $next)
    {	
        return $next($request);
    }
}
</pre?>

Output will be like this:-

This middleware would perform its task after the request is handled by the application.

<?php namespace App\Http\Middleware;
use Closure;

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

        echo "User";

        return $response;
    }
}
</pre?>

Output will be like this:-

3. Registering Middleware.

Global Middleware

you want a middleware to run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/kernel.php class.

Assigning Middleware To Routes

You would like to assign middleware to specific routes, you should first assign the middleware a key in your app/Http/kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing.

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

Once the middleware has been defined in the kernel, you can use the middleware method to assign middleware to a route.

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

You may also assign multiple middleware to the route.

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

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

use App\Http\Middleware\CheckAge;
Route::get('admin/profile', function () {
    //
})->middleware(CheckAge::class);

Middleware Groups

Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may do this using the $middlewareGroups property of your HTTP kernel.

Out of the box, Laravel comes with web and api middleware groups that contains common middleware you may want to apply to your web UI and API routes.

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

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

Route path:-

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

Route::group(['middleware' => ['web']], function () {
    //
});

4. Middleware Parameters.

Middleware can also receive additional parameters. For example, if your application needs to verify that the authenticated user has a given "role" before performing a given action, you could create a CheckRole middleware that receives a role name as an additional argument.

Additional middleware parameters will be passed to the middleware after the $next argument.

Middleware Parameter Example

<?php namespace App\Http\Middleware;

use Closure;

class CheckRole
{
    public function handle($request, Closure $next, $role)
    {
        if (! $request-?>user()->hasRole($role)) {
            // Redirect...
        }
        return $next($request);
    }
}

Route Path:-

Route::put('post/{id}', function ($id) {
    //
})->middleware('role:editor');

5. Terminable Middleware.

Sometimes a middleware may need to do some work after the HTTP response has been sent to the browser. For example, the "session" middleware included with Laravel writes the session data to storage after the response has been sent to the browser. If you define a terminate method on your middleware, it will automatically be called after the response is sent to the browser.

Middleware Terminable Example

<?php namespace Illuminate\Session\Middleware;
use Closure;

class StartSession
{
    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response)
    {
        // Store the session data...
    }
}
</pre?>

The terminate method should receive both the request and the response. Once you have defined a terminable middleware, you should add it to the list of route or global middleware in the app/Http/kernel.php file.

Laravel Tutorial