Laravel 5.7 如何在控制器构造方法中根据vendor_id条件赋值属性
结论
该需求无法直接在控制器构造方法的顶层逻辑中实现,同时你提供的代码本身也存在数组拼接的语法问题。
原因说明
Laravel 5.3及以上版本中,控制器的构造方法会在请求解析、路由参数注入、模型绑定完成之前运行,此时你无法从控制器属性、请求实例中拿到vendor_id这类动态参数,所以判断逻辑永远不会按预期触发。
另外你当前使用array_push拼接数组的写法是错误的:array_push会把整个$noVendorInformation/$vendorInformation数组作为单个元素推入$showFields,最终得到的是二维数组,不符合视图渲染的要求,应该用array_merge做数组合并。
实现方案
方案1:逻辑移到具体控制器动作(推荐)
把$showFields的组装逻辑放到实际处理请求的动作方法中,此时已经完成了参数解析和模型查询,可以直接拿到vendor_id:
protected $showFields = []; protected $vendorInformation = [...]; protected $noVendorInformation = [...]; public function __construct(QuoteService $quoteService) { parent::__construct(); $this->quoteService = $quoteService; } // 示例为详情页动作,可根据实际业务替换为你的方法 public function show($quoteId) { $quote = \App\Quote::findOrFail($quoteId); $targetVendorId = 10; // 替换为你指定的对比值 // 组装展示字段 $this->showFields = array_merge( $this->showFields, $quote->vendor_id === $targetVendorId ? $this->noVendorInformation : $this->vendorInformation ); // 传递参数到视图 return view('quote.show', [ 'showFields' => $this->showFields, 'quote' => $quote ]); }
方案2:构造方法中注册中间件实现全局自动处理
如果该控制器下所有动作都需要用到这个逻辑,可以在构造方法中注册闭包中间件,中间件会在请求解析完成后运行,此时可以正常获取参数:
public function __construct(QuoteService $quoteService) { parent::__construct(); $this->quoteService = $quoteService; $targetVendorId = 10; // 替换为你指定的对比值 $this->middleware(function ($request, $next) use ($targetVendorId) { // 按需从路由参数/请求参数/查询到的模型中取vendor_id $vendorId = $request->route('vendor_id'); $this->showFields = array_merge( $this->showFields, $vendorId === $targetVendorId ? $this->noVendorInformation : $this->vendorInformation ); return $next($request); }); }
内容的提问来源于stack exchange,提问作者jcobo1
相关产品推荐
相关产品推荐

