Laravel 路由错误 Bad Method Call Exception

Laravel routing slug error Bad Method Call Exception

我正在尝试创建一个包含三个 slug 的路由,其中​​包括类别、品牌名称和产品名称。

web.php

Route::get('/shop/{category:slug}/{brand:slug}/{product:slug}', [ProductController::class, 'index']);

控制器

<?php

namespace App\Http\Controllers;

use App\Brand;
use App\Category;
use App\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index(Category $category, Brand $brand, Product $product)
    {
        $product = Product::where('id', $product->id)->with('related', function($q) {
            $q->with('brand')->with('categories');
        })->with('brand')->first();

        return view('product', compact('product', 'category'));
    }
}

出于某种原因,我得到了这个错误,我不明白为什么。

BadMethodCallException Call to undefined method App\Category::brands()

路由解析器假设参数都相互关联。来自 the documentation:

When using a custom keyed implicit binding as a nested route parameter, Laravel will automatically scope the query to retrieve the nested model by its parent using conventions to guess the relationship name on the parent.

因此,您应该在 Category 模型中设置 brands() 关系,并在 Brand 模型中设置 products() 关系。

如果无法建立关系,只需停止使用路由模型绑定并手动进行:

Route::get('/shop/{category}/{brand}/{product}', [ProductController::class, 'index']);
<?php

namespace App\Http\Controllers;

use App\Brand;
use App\Category;
use App\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index(string $category, string $brand, string $product)
    {
        $category = Category::where('slug', $category);

        $product = Product::where('slug', $product)
            ->with(['category', 'brand'])->first();

        return view('product', compact('product', 'category'));
    }
}