Laravel跨控制器调用带Request参数方法返回空数组如何解决
问题原因
Laravel 的 Request 类的all()方法读取的是请求实例内部的参数存储容器(包含查询字符串、POST提交、JSON上传等参数),你直接通过$input->param1 = xxx的方式是给Request对象动态挂载公共属性,并没有将参数写入到Request的内部参数容器中,因此调用all()方法时无法读取到你赋值的参数,就会返回空数组。
正确实现方案
方案1:直接修复现有代码(快速可用)
使用Request类自带的replace()或merge()方法将参数写入到内部容器,修改后的Controller1代码如下:
public function get() { $call = new Controller2(); $input = new Request(); // 批量写入参数到Request内部容器 $input->replace([ 'param1' => $param1, 'param2' => $param2 ]); $response = $call->index($input); }
此时Controller2中调用$request->all()就能正常读取到参数,也可以正常使用$request->input('param1')等Request原生方法。
方案2:最佳实践(推荐)
跨控制器调用方法属于强耦合的代码设计,更合理的方式是将两个控制器共用的逻辑抽离到独立的服务类(Service)或者动作类(Action)中,两个控制器都依赖该公共类执行业务逻辑,避免控制器之间的直接依赖:
- 新建
app/Services/CommonService.php
namespace App\Services; class CommonService { public function handleIndex($param1, $param2) { // 原Controller2的index方法业务逻辑写在这里 dd([$param1, $param2]); } }
- 两个控制器都注入该服务调用即可:
// Controller1 中调用 public function get(\App\Services\CommonService $service) { $response = $service->handleIndex($param1, $param2); } // Controller2 中调用 public function index(Request $request, \App\Services\CommonService $service) { return $service->handleIndex( $request->input('param1'), $request->input('param2') ); }
内容的提问来源于stack exchange,提问作者Sowndhar Kumar R
相关产品推荐
相关产品推荐

