Andreas94's avatar

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

Hi guys, I have been carrying this error for several months, which is not a problem but I want to solve it:

In Route.php line 917:

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

I read that you have to comment on the code in route / api.php

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

after giving the command php artisan route:cache

But now I get the error:

In Route.php line 917:

  Unable to prepare route [{fallbackPlaceholder}] for serialization. Uses Closure.
0 likes
10 replies
Talinon's avatar

You can't cache routes if you are using a closure. The closure is this part:

function (Request $request) {
    return $request->user();
}

Instead, if you move the code into a controller you'll be able to cache the routes and eliminate the error.

1 like
Hadayat's avatar

I am not using any closure but it throw closure exception

 Unable to prepare route [api/user] for serialization. Uses Closure.
DennisEilander's avatar

@hadayat Make sure to check all your routes in your project. This error means that a route is making use of a closure.

Take a look at the output of php artisan route:list and check if there is any Closure in that list.

1 like
Hadayat's avatar

My Route File

Route::get('/send', 'MailController@index');
Route::get('/sendmail', 'MailController@sendMail');
DennisEilander's avatar

@hadayat did you ran php artisan route:list ? This wil show you all routes and then you can determine if there is any closure in that route. Can you submit the output of that command?

zylwin's avatar

Check your routes/api.php there's a default route that laravel adds as an example for you which uses a closure. Please remove or comment that route and test again.

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

@zylwin You are right. I disabled in Api.php and it works for me. Thank you very much dear.

1 like
ugintl's avatar

@zylwin It worked, but now I am getting another error Unable to prepare route [js/lang.js] for serialization. Uses Closure. I am running thee command "php artisan optimize"

shiprocket_devs's avatar

@hadayat @zylwin After a force restart of my laptop my laravel application stopped responded, I tried to make all changes suggested by you guys but still I am getting the same thing.

Unable to prepare route [/] for serialization. Uses Closure. {"exception":"[object] (LogicException(code: 0): Unable to prepare route [/] for serialization. Uses Closure. at /var/www/html/XXXXX/vendor/laravel/framework/src/Illuminate/Routing/Route.php:917) Please suggest me if your issue is resolved. Thanks in advance

Please or to participate in this conversation.