如何将路由中的值传递给控制器​​以在 Laravel 中的视图中使用?

How do I pass a value in my Route to the Controller to be used in the View in Laravel?

我有 2 个名为 MatchRoster 的实体。 我的比赛路线是这样的

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

为了view/create每场特定比赛的球队,我添加了比赛名单的路线,如下所示:

Route::get('/matches/'.'{id}'.'/roster/', [App\Http\Controllers\RosterController::class, 'index']);

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

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

我需要它来做一些事情。首先,我需要在名册上进行搜索 table 按具有该值的列进行过滤,这样我就可以只显示属于那场比赛的球员。

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

我该怎么做?

#1 您可以通过 request()->route('parameter_name').

获取在您的路线上定义的路线参数
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);