laravel 如何为电子商务的多个类别创建动态路由?

How to create a dynamic route for multiple categories of ecommerce in laravel?

我想:

  1. 创建动态路由逻辑来处理 URL 中的类别和子类别。
  2. 将动态变量发送到产品模型中的 where 子句

Web.php 路由文件:

Route::prefix("products")->group(function () {
    Route::get('{category_one}/{category_two}',[ProductsController::class,'index'])->where(['category_one'=> '[A-Za-z]+','category_two'=>'[A-Za-z]+']);
});

ProductsController.php

use App\Models\Products;
public function index()
    {
        $products = new Products;
        $products=$products->getProducts();
        return view('pages.products')->with(['products'=>$products]);
    }

Products.php 型号

use Illuminate\Support\Facades\DB;
public function getProducts(){
        $products = DB::table('products')->where([['category_one', "{category_one}"],['category_two', "{category_two}"]])->latest()->get();
        return $products;
    }

我在从 URL 动态获取 {category_one} 和 {category_two} 时遇到问题。

错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'category_two' in 'where clause' (SQL: select * from products where (category_one = {category_one} and category_two = {category_two}) order by created_at desc)

可以从请求对象中获取路由参数

use App\Models\Products;
use Illuminate\Http\Request;

public function index(Request $request)
{
    $categoryOne = $request->route('category_one');
    $categoryTwo = $request->route('category_two');

    $products = Products::where([
        ['category_one', $categoryOne], 
        ['category_two', $categoryTwo]
    ])->latest()->get();

    
    return view('pages.products',['products'=>$products]);
}