1

I have installed laravel 7 in my local server. When I run php artisan route:cache command then laravel return error:

LogicException

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

enter image description here

How I can solve this problem?

I tried by running artisan commands:

php artisan config:cache
php artisan config:clear
php artisan cache:clear
composer dumpautoload

Here is content routes/api.php:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
Andreas Hunter
  • 4,504
  • 11
  • 65
  • 125
  • move call back to in contoroller then it will fixed `Route::middleware('auth:api')->get('/user', 'AnyController@index'); – Kamlesh Paul Mar 07 '20 at 04:56
  • Why if closure routes return error, laravel developers passed closure route to `api.php` file then? @KamleshPaul – Andreas Hunter Mar 07 '20 at 04:59
  • This problem was not in previous versions of the framework. – Andreas Hunter Mar 07 '20 at 05:01
  • Does this [link](https://stackoverflow.com/questions/45266254/laravel-unable-to-prepare-route-for-serialization-uses-closure) help? Closures can't be serialised, so you can't cache your routes if they are using Closures. – Qumber Mar 07 '20 at 06:06

1 Answers1

7

You can't cache your routes if they are using Closure.

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

Official docs (This is not new to Laravel 7) https://laravel.com/docs/5.8/deployment#optimization.

To make route:cache work, you may want to replace all requests using Closures to use a Controller method instead.

The route above, would then be like:

Route::middleware('auth:api')->get('/user', 'UserController@show');

And the controller method UserController@show would be like:

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

Hope this helps! :)

Qumber
  • 13,130
  • 4
  • 18
  • 33
  • 1
    indeed that was the issue for me, api.php and web.php had closures like you said that caused this – Omar Jun 07 '21 at 14:29