Middleware can skillfully filter requests and secure the application or RESTful API from unwanted requests. It can also perform logging and redirect any requests that fall within a certain criteria.
Middleware can also provide added functionality to the existing application. For example, Laravel provides the EncryptCookies
and AddQueuedCookiesToResponse
middleware to deal with cookies, while StartSession
and ShareErrorsFromSession
deal with sessions.
The code inside AddQueuedCookiesToResponse
does not filter the request, but rather adds to it:
public function handle($request, Closure $next) { $response = $next($request); foreach ($this->cookies->getQueuedCookies() as $cookie) { $response->headers->setCookie($cookie); } return $response; }