Laravel 8调用redirect()->action('BookingController@index')报错未定义问询
问题原因
Laravel 8版本开始对路由注册逻辑做了调整,默认取消了RouteServiceProvider中自带的$namespace属性,框架不再自动为控制器路径拼接命名空间前缀,所以旧版本支持的控制器名@方法名字符串形式的action调用写法就无法解析到对应的控制器类,因此抛出未定义的错误。
解决方法
有3种常用的解决方案,按需选择即可:
- 方案1:直接传入控制器类的完全限定名,不需要改动路由配置
把原有代码修改为:
如果文件顶部已经引入了BookingController的命名空间,可以简化为:return redirect()->action([\App\Http\Controllers\BookingController::class, 'index']);// 顶部先引入 use App\Http\Controllers\BookingController; // 方法内调用 return redirect()->action([BookingController::class, 'index']); - 方案2:恢复旧版本的自动命名空间拼接逻辑
打开app/Providers/RouteServiceProvider.php文件,先在类中声明$namespace属性:
再找到protected $namespace = 'App\Http\Controllers';boot方法,给web路由组加上命名空间前缀配置:
配置完成后原有$this->routes(function () { Route::middleware('web') ->namespace($this->namespace) // 加上这一行配置 ->group(base_path('routes/web.php')); });'BookingController@index'的写法就可以正常使用了。 - 方案3:如果已经给对应路由定义了命名别名,直接用路由别名跳转更方便
假设路由文件中已经定义了如下路由:
直接用别名跳转的写法更简洁:Route::get('/bookings', [BookingController::class, 'index'])->name('bookings.index');return redirect()->route('bookings.index');
内容的提问来源于stack exchange,提问作者askermad789
相关产品推荐
相关产品推荐

