There are two types of middleware in the Laravel application. One works before the response and the other works after the response. In this example, we will discuss terminable middleware which works after the server response.

Sometimes you may need to perform a task after getting the response from the server in your Laravel application. In this case, we can use terminable middleware. If you know how terminable middleware works and how to use terminable middleware, then you will understand when to use terminable middleware in the Laravel application.

In this tutorial, we will see how to use terminable middleware in laravel and what is terminable middleware in laravel. We can use the terminate method in our middleware to get the help of terminable middleware. This method accepts two middleware, request and response. Look at the example of terminable middleware.

<?php
 
namespace Illuminate\Session\Middleware;
 
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
 
class TestMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        return $next($request);
    }
 
    /**
     * Handle tasks after the response has been sent to the browser.
     */
    public function terminate(Request $request, Response $response): void
    {
        //your code after server response
    }
}

 

Now, this middleware may need to do some work after the HTTP response has been sent to the browser with this terminate method. 

 

Read also: Complete Explanation With Example On Laravel Middleware

 

Conclusion

Now we know what is terminable middleware in laravel and how to use terminable middleware in laravel. Hope this laravel terminable middleware example will help you to understand types of middleware in laravel.