Laravel 7:无法为序列化准备路由 [api/user]。使用闭包。 (逻辑异常)[重复]

Posted

技术标签:

【中文标题】Laravel 7:无法为序列化准备路由 [api/user]。使用闭包。 (逻辑异常)[重复]【英文标题】:Laravel 7: Unable to prepare route [api/user] for serialization. Uses Closure. (LogicException) [duplicate] 【发布时间】:2020-06-19 19:18:32 【问题描述】:

我已经在本地服务器上安装了 laravel 7。当我运行php artisan route:cache 命令时,laravel 返回错误:

逻辑异常

无法为序列化准备路由 [api/user]。使用闭包。

我该如何解决这个问题?

我尝试运行工匠命令:

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

这里是内容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();
);

【问题讨论】:

将调用移回控制器,然后它将修复 `Route::middleware('auth:api')->get('/user', 'AnyController@index'); 为什么如果闭包路由返回错误,laravel 开发者将闭包路由传递给api.php 文件呢? @KamleshPaul 以前版本的框架没有这个问题。 这link 有帮助吗?闭包不能被序列化,所以如果你的路由使用闭包,你就不能缓存它们。 【参考方案1】:

如果你的路由使用了闭包,你就不能缓存它们。

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

官方文档(这对 Laravel 7 来说并不新鲜)https://laravel.com/docs/5.8/deployment#optimization。

要使route:cache 工作,您可能希望使用闭包替换所有请求以改用控制器方法。

上面的路线会是这样的:

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

控制器方法UserController@show 如下:

public function show(Request $request)

    return $request->user();

希望这会有所帮助! :)

【讨论】:

这确实是我的问题,api.php 和 web.php 像你说的那样有关闭导致这个

以上是关于Laravel 7:无法为序列化准备路由 [api/user]。使用闭包。 (逻辑异常)[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Laravel - 错误“无法为序列化准备路由 [/]。使用闭包。”

无法为序列化准备路由 [api/user]。使用闭包

Laravel 5 - 带有消息“无法准备路由”的异常“LogicException”

无法为 api 路由 laravel 设置 cookie

Laravel 无法保护 API 路由

在 laravel 5.6 中无法使用邮递员使用 api 路由