Laravel 5: Middleware before & after into routes

Federico González Brizzio picture Federico González Brizzio · Jul 9, 2015 · Viewed 18.9k times · Source

I have two Middlewares: beforeCache & afterCache, boths registered on Kernel.

I want to call them into routes in this order: 1. beforeCache 2. myController 3. afterCache

If I define a route like this:

Route::get('especies/{id}', [
    'middleware' => 'beforeCache', 
    'uses' => 'MyController@myMethod', 
    'middleware' => 'afterCache', 
]);

beforeCache don't executes because afterCache is redefining the same array key middleware.

How should I do that? Thanks!

Answer

Sieabah picture Sieabah · Jul 9, 2015

I'll assume you're using 5.1 in this, but what you're doing is essentially trying to define an array of attributes on the route. The brackets [] are just a shorthand version of saying array(...).

From the documentation (http://laravel.com/docs/5.1/middleware#defining-middleware) specifically the Before / After Middleware you simply just need to return a certain way.

For Before middlewares you do your code and return the next request after your code executes.

public function handle($request, Closure $next)
{
    // Perform action

    return $next($request);
}

For After middleware you handle the rest of the request and then your code executes and finally return the response.

public function handle($request, Closure $next)
{
    $response = $next($request);
    // Perform action
    return $response;
}

The route would end up looking like this,

Route::get('especies/{id}',[
    'middleware' => [
        'beforeCache',
        'afterCache'
    ],
    'uses' => 'MyController@myMethod'
]);