laravel - 如何将多个值从控制器传递到视图
问题描述
我有一个表单,其中有许多下拉列表,在创建和编辑记录时从不同的表中填充这里是代码
<?php
class ParticipantController extends Controller
{
/**
* Store a newly created resource in storage.
*/
public function create(Participant $participant)
{
$this->authorize('create',$participant);
$events = Event::get_name_and_id();
$wards =Ward::get_name_and_id();
$individuals = Individual::get_name_and_id();
$organizations = Organization::get_name_and_id();
$roles = ParticipantRole::get_name_and_id();
$groups = Group::get_name_and_id();
return view('participants.create', compact('events','wards','individuals','organizations','participant','roles','groups'));
}
/**
* Show the form for editing the specified resource.
*/
public function edit(Participant $participant)
{
$events = Event::get_name_and_id();
$wards =Ward::get_name_and_id();
$individuals = Individual::get_name_and_id();
$organizations = Organization::get_name_and_id();
$roles = ParticipantRole::get_name_and_id();
$groups = Group::get_name_and_id();
return view('participants.edit', compact('events','wards','individuals','organizations','participant','roles','groups'));
}
}
你可以从代码中看到表单从 6 个表中获取数据作为下拉列表,这里是如何管理的。它工作正常,但阅读和理解太多了
解决方案
您可以在单独的方法中重构冗余代码,例如
class ParticipantController extends Controller
{
public function populate($function_name, $participant) {
$events = Event::get_name_and_id();
$wards =Ward::get_name_and_id();
$individuals = Individual::get_name_and_id();
$organizations = Organization::get_name_and_id();
$roles = ParticipantRole::get_name_and_id();
$groups = Group::get_name_and_id();
$data = compact('events','wards','individuals','organizations','roles' ,'groups', 'participant');
return view('participants.' . $function_name , $data);
}
/**
* Store a newly created resource in storage.
*/
public function create(Participant $participant) {
$this->authorize('create',$participant);
return $this->populate(__FUNCTION__, $participant);
}
/**
* Show the form for editing the specified resource.
*/
public function edit(Participant $participant) {
return $this->populate(__FUNCTION__, $participant);
}
}
推荐阅读
- swift - SLServiceTypeTwitter' 已弃用:首先在 iOS 11.0 中弃用
- python - 带有布尔值或的 Pandas groupby
- python - 从生成器中保持运行总数的最pythonic方法是什么?
- http - HTTP请求返回502状态码时Nginx返回“502 Bad GateWay”+requestUrl
- mysql - 包含按日期排序的列名的派生列
- c# - GemBox 文档将特殊字符添加到 boomark 中
- scala - 使用scala正则表达式提取[]内的所有字符串
- powershell - 更改 AD 用户组成员资格
- macos - 调用应用程序名称 FMX OSX
- hibernate - Hibernate 没有为具有支持属性的 Kotlin 属性创建连接表