Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

wanderlusted's avatar

Laravel 7 route caching for groupped routes crashes

I'm trying to speed up my Laravel 7 webapp by caching the routes. As caching does not work with route closures, I converted all my closure based routes in the web.php file to controller based routes. The only closures I still have in the file are in the second parameter of the Route:group method:

//Iterate over each language prefix 
foreach( $all_langs as $prefix ){

    Route::group(
        [    
            'prefix' => $prefix . '/office', 
            'middleware' => 
                [
                    'initLocale',
                    'auth', 
                    'logManualInteractions' 
                ],    
        ], 
        function() use ($prefix) {
            $langPrefix = '';
            if (!empty($prefix)) {
                $langPrefix = $prefix . '.';
            }

        //Profile page
        Route::get('profile', 'Backoffice\GNGProfileController@show')->name('office.' . $langPrefix .'profile.show');
        Route::post('profile', 'Backoffice\GNGProfileController@store')->name('office.' . $langPrefix .'profile.store');

        });
}

This article made me believe that this should be okay. Unfortunately I still get the below error message when trying to run php artisan route:cache :

  LogicException 

  Unable to prepare route [api/user] for serialization. Uses Closure.

  at /home/customer/www/staging.gonativeguide.com/gng2-core/vendor/laravel/framework/src/Illuminate/Routing/Route.php:1150
    1146|      */
    1147|     public function prepareForSerialization()
    1148|     {
    1149|         if ($this->action['uses'] instanceof Closure) {
  > 1150|             throw new LogicException("Unable to prepare route [{$this->uri}] for serialization. Uses Closure.");
    1151|         }
    1152| 
    1153|         $this->compileRoute();
    1154| 

I checked with route:list command that none of my routes are closure based, so I have to think that the problem is related to the closures in the group method signature.

Is there any way to fix this? Can I use route caching for grouped routes? Thanks!

0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122

did you check api.php?

1 like
wanderlusted's avatar

Thanks!!! Commenting out the below lines in the api.php solved my problem! Do you happen to know, what these lines are for? I think it was part of the default installation, so I'm not sure if it is just an example API call that I can simply comment out without any side-effects in my project. Thanks!

Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); });

Please or to participate in this conversation.