arubacao's avatar

[Lumen] Terminable Middleware - handle() gets called, but terminate doesn't. Why?

Unfortunately i can't get my middleware work as desired..

Necessary Code: routes.php

$app->group(['prefix' => 'api/v1', 'namespace' => 'App\Http\Controllers\v1\History', 'middleware' => 'storeHistorySession'], function($app) {
    $app->post('history','HistoryController@create');
});

middleware:

class StoreHistorySessionMiddleware implements TerminableMiddleware
{
    public function handle($request, Closure $next)
    {
        Log::debug('Test#handle() called');
        return $next($request);
    }

    public function terminate($request, $response)
    {
        Log::debug('Test#terminate() called');
    }
}

The only log that can be found in lumen.log is [2015-09-09 19:22:33] lumen.DEBUG: Test#handle() called

BTW: I'm running it on homestead

What am I doing wrong?

Cheers, arubacao

0 likes
5 replies
rwdevguy's avatar

Have you added the middleware to your bootstrap/app.php file?

arubacao's avatar

Yes, i have:

bootstrap/app.php

 $app->routeMiddleware([
     //....
     'storeHistorySession'      => 'App\Http\Middleware\v1\History\StoreHistorySessionMiddleware'
 ]);
thomaskim's avatar
Level 41

@arubacao According to the docs:

http://lumen.laravel.com/docs/middleware#terminable-middleware

Once you have defined a terminable middleware, you should add it to the list of global middlewares in your bootstrap file.

It needs to be added to the global middleware list, not your route middleware list. A global middleware is something that runs on EVERY http request so I'm not sure if that's what you want to do. Anyway, add it to your $app->middleware list. Also, you do not need to define it in your routes file because it will trigger on every http request.

1 like
orrd's avatar

Just in case anyone else is confused, the current Laravel docs also say "you should add it to the list of global middlewares in your bootstrap file", but at least with Laravel, you can use terminable middleware with route middleware (it doesn't have to be in your global middleware list). But that might be true for Lumen (I don't know about Lumen).

Please or to participate in this conversation.