Search code examples
laravel-5.5kohana-3

Is there any substitute method in laravel for before() and after() methods of kohana?


In kohana we use before() and after() methods which are called automatically before and after the called function.

Is there any substitute or equivalent method in laravel which perform these steps.


Solution

  • You can use Before & After Middlewares.

    A middleware can run before or after a request is processed.

    That depends on how the middleware handle() function is constructed, for example this is a before middleware, i.e. it runs before request is handled by the application (controller or route function):

    <?php
    namespace App\Http\Middleware;
    use Closure;
    
    class BeforeMiddleware
    {
        public function handle($request, Closure $next)
        {
            // Perform action
            return $next($request);
        }
    }
    

    And this one run after the request has been processed by the application (controller or Route function) but before the response:

    <?php
    namespace App\Http\Middleware;
    use Closure;
    
    class AfterMiddleware
    {
        public function handle($request, Closure $next)
        {
            $response = $next($request);
            // Perform action
            return $response;
        }
    }
    

    You can register middlewares per route, per controller or global for the application. You can find extensive documentation on middleware in the Laravel Docs