What Is Terminable Middleware In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 17-09-2020

Terminable middleware performs some task after the response has been sent to the browser. This can be accomplished by creating a middleware with terminate method in the middleware. Terminable middleware should be registered with global middleware. The terminate method will receive two arguments $request and $response. Terminate method can be created as shown in the following code.

What Is Terminable Middleware In Laravel With Example

Sometimes a middleware may need to do some work after the HTTP response has been sent to the browser. If you define a terminate method on your middleware and your web server is using FastCGI, the terminate method will automatically be called after the response is sent to the browser:

<?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...
    }
}
 

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.

When calling the terminate method on your middleware, Laravel will resolve a fresh instance of the middleware from the service container. If you would like to use the same middleware instance when the handle and terminate methods are called, register the middleware with the container using the container's singleton method. Typically this should be done in the register method of your AppServiceProvider.php:

use App\Http\Middleware\TerminableMiddleware;

/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton(TerminableMiddleware::class);
}
 

Lets we create 

1.Create TerminateMiddleware using below command.

php artisan make:middleware TerminateMiddleware


2.Open app/Http/Middleware/TerminateMiddleware.php. and implement code as below

<?php

namespace App\Http\Middleware;
use Closure;

class TerminateMiddleware {
    public function handle($request, Closure $next) {

        echo "We learn about Terminable Middleware";
        return $next($request);
    }

    public function terminate($request, $response) {
        echo "<br>Executing statements of terminate method of TerminateMiddleware.";
    }
}


3.Register the TerminateMiddleware in app\Http\Kernel.php file. as below 
 
protected $routeMiddleware = [
   .......
    'terminate' => \App\Http\Middleware\TerminateMiddleware::class,
   ........
];


4.Now cal terminate middleware in routes.php file.open web.php file and implement code as below 
web.php

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

 

Related Post