如何将Route中的值传递给要在Laravel中的View中使用的Controller



我有两个实体,分别称为MatchRoster。我的比赛路线就像这个

http://localhost:8888/app/public/matches(索引(http://localhost:8888/app/public/matches/14(显示(

为了查看/创建每一场特定比赛的球队,我添加了比赛名单的路线,如下所示:

Route::get('/matches/'.'{id}'.'/roster/', [AppHttpControllersRosterController::class, 'index']);

现在我需要我的URL中的{id}将其传递给这里的控制器:

public function index()
{
return view('roster.index');
}

我有几件事需要它。首先,我需要在名册表上搜索一个具有该值的列进行筛选,这样我就只能显示属于该比赛的球员。

其次,我需要将它传递到视图,以便在我的商店中使用它并更新表单。我想从同一索引视图中添加或删除球员。

我该怎么做?

#1您可以通过request()->route('parameter_name')获取在ur路由上定义的路由参数。

public function index()
{
// get {id} from the route (/matches/{id}/roster)
$id = request()->route('id');
}

#2您可以使用return view(file_name, object)传递数据对象

public function index()
{
// get {id} from the route (/matches/{id}/roster)
$id = request()->route('id');
// query what u want to show
// dunno ur models specific things, so just simple example. 
$rosters = Roster::where('match_id', '=', $id);
// return view & data
return view('roster.index', $rosters);
}

#3不仅可以进行索引,还可以进行其他操作(创建、存储、编辑、更新(

此外,强烈建议先用简单的例子学习官方教程。比如博客、董事会等。。您需要了解构建Laravel应用程序的要点。

大多数时候,我更喜欢命名路线。

Route::get('{bundle}/edit', [BundleController::class, 'edit'])->name('bundle.edit');

控制器内

public function edit(Bundle $bundle): Response
{
// do your magic here
}

你可以通过呼叫路线

route('bundle.edit', $bundle);

最新更新