Hexor
Hexor

Reputation: 545

How does Laravel know whether a middleware should be run after the request handled?

I read the source code, and there is only a pipeline which reads all middlewares as an array. These middlewares should be run before the request dispatchToRouter.

return (new Pipeline($this->app))
    ->send($request)
    ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
    ->then($this->dispatchToRouter()); 

However, if I created an after-middleware, the after-middleware should be run after the request handled. here and when the after-middleware being execute in the laravel source code?

Upvotes: 1

Views: 2310

Answers (1)

Sagar Gautam
Sagar Gautam

Reputation: 9369

According to laravel official documentation,

Whether a middleware runs before or after a request depends on the middleware itself.

So, basically it depends on the handle function of the middleware. Normally we execute middleware just before handling the request like this:

public function handle($request, Closure $next)
{
    // Perform some operation for Ex. checking user role

    return $next($request);
}

In above function, we execute some operation before sending request to perform operation.

In the another case, middleware would perform its task after the request is handled by the application like this:

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

    // Perform some operation after the request is handled by the application

    return $response; /* finally, response is returned */
}

In summary, In before middleware, we perform some operations at first and then send request to the application to get response which is returned to client end. In after middlware, we send request to the application at first to get response then we perform our actions and finally we return the response from middleware to client end.

You can see official docs: https://laravel.com/docs/5.8/middleware#defining-middleware

Upvotes: 7

Related Questions