You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lumen部署报错:Undefined variable $router 求助

问题

部署Lumen个人网站后出现报错,本地VS Code运行正常。报错信息:

[28-Nov-2023 13:12:17 UTC] PHP Warning: Undefined variable $router in /home/xx/portfolio/routes/web.php on line 16
[28-Nov-2023 13:12:17 UTC] PHP Fatal error: Uncaught Error: Call to a member function get() on null in /home/xx/portfolio/routes/web.php:16

当前web.php代码:

<?php

/** @var \Laravel\Lumen\Routing\Router $router */

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
$router = app('router');
$router->get('/', function () use ($router) {
    return view('portfolio');
});

$router->get('/blog', function () {
    return view('blog');
});
解决方法

问题出在你手动添加的$router = app('router');这行代码上。Lumen框架加载路由文件时,会自动注入$router变量,无需手动获取。生产环境中,手动调用app('router')可能因容器初始化顺序问题返回null,进而触发报错。

直接删除$router = app('router');这一行即可,保留框架默认的注释和路由定义。修正后的web.php代码:

<?php

/** @var \Laravel\Lumen\Routing\Router $router */

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
$router->get('/', function () use ($router) {
    return view('portfolio');
});

$router->get('/blog', function () {
    return view('blog');
});

另外,第一个路由闭包里的use ($router)可以去掉,因为闭包内并未用到$router变量:

$router->get('/', function () {
    return view('portfolio');
});

内容的提问来源于stack exchange,提问作者N D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 02:20:34