Laravel 8 上的 ArgumentCountError

ArgumentCountError on Laravel 8

我正在使用 laravel 8,当我这样写路线时:

web.php

Route::match(['get', 'post'], '/', [PageController::class, 'index']);

Route::match(['get', 'post'], '/tshirt', [PageController::class, 'productCategory']);
Route::match(['get', 'post'], '/electronic', [PageController::class, 'productCategory']);

Route::match(['get', 'post'], '/tshirt/{slug}', [PageController::class, 'detail']);
Route::match(['get', 'post'], '/electronic/{slug}', [PageController::class, 'detail']);

控制器是这样的:

PageController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PageController extends Controller
{
    public function index()
    {
        $data = [
            'title' => 'Dashboard',
        ];

        return view('pages.index', $data);
    }

    public function productCategory($category)
    {
        # code...
    }

    public function detail($category, $detail)
    {
        # code...
    }
}

我想要的是,如果当用户位于 url '/tshirt' 或 '/electronic' 时,thshirt 或 electronic 将包含在 PageController::productCategory[ 的 $category 参数中=14=]

类似地,当用户输入“/tshirt/nameoftshirt”时,PageController::detail 控制器将用 'tshirt' 填充 $category 参数,用 'nameoftshirt'[= 填充 $slug 14=]

显示此错误:

ArgumentCountError
Too few arguments to function App\Http\Controllers\PageController::productCategory(), 0 passed in D:\Programing\Web\laraApp\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 1 expected

如何获取路由以将主要参数传递给控制器​​?

您必须使主要类别动态化,然后您可以像现在尝试的那样在控制器中捕获它。这样您就不必为每个类别创建路由。

Route::match(['get', 'post'], '/{category}', [PageController::class, 'productCategory']);
Route::match(['get', 'post'], '/{category}/{slug}', [PageController::class, 'detail']);

然后在控制器中

public function productCategory($category)
{
    dd($categoty); // prints tshirt when you hit the url /tshirt
}

public function detail($category, $detail)
{
    dd($categoty, $detail); // prints tshirt and nameoftshirt when you hit the url /tshirt/nameoftshirt
}