我正在嘗試創建一條包含三個 slug 的路線,其中包括類別、品牌名稱和產品名稱。
網頁.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呼叫未定義的方法 App\Category::brands()
uj5u.com熱心網友回復:
路由決議器假設引數都相互關聯。從檔案:
當使用自定義鍵控隱式系結作為嵌套路由引數時,Laravel 將自動將查詢范圍限定為通過其父級檢索嵌套模型,使用約定來猜測父級上的關系名稱。
所以你應該brands()在你的Category模型中建立一個products()關系,以及你的Brand模型中的一個關系。
如果無法建立關系,只需停止使用路由模型系結并手動進行:
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'));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/370928.html
上一篇:使行擴展到可滾動父級的寬度
