【问题标题】:Laravel routing slug error Bad Method Call ExceptionLaravel 路由 slug 错误 Bad Method Call Exception
【发布时间】:2022-01-08 01:49:06
【问题描述】:

我正在尝试创建一个包含三个 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 调用未定义的方法 App\Category::brands()

【问题讨论】:

  • 奇怪,我在这里的代码中没有看到brands()。请发布堆栈跟踪,以便我们查看错误所在。它可能在您的一个模型中。
  • 您是否偶然在刀片文件中调用了$category-&gt;brands
  • 不,我不是,如果我从函数中删除Brand $brand,它就可以正常工作。

标签: php laravel laravel-routing


【解决方案1】:

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

当使用自定义键控隐式绑定作为嵌套路由参数时,Laravel 将自动限定查询范围,以通过其父级检索嵌套模型,使用约定猜测父级上的关系名称。

因此,您应该在 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'));
    }
}

【讨论】:

  • 我了解,但是品牌与品类没有关系,只有产品。所以要解决这个问题,我应该只使用 slug 并在函数内通过查询找到品牌。
  • 明白了,一个品牌会有很多不同品类的产品。不幸的是,URL 的设置方式,Laravel 假设了一个关系。文档没有提到任何覆盖或禁用该行为的方法。
  • 是的,如果您需要 URL 中的 slug 而不是 ID,您可以完全摆脱路由模型绑定并手动进行查找。尽管查看您的控制器,但您甚至没有使用 $category$brand 变量。
  • 我在紧凑函数中使用$category,我只是对错误感到非常困惑。感谢您指出!
猜你喜欢
  • 2019-04-28
  • 1970-01-01
  • 2018-12-21
  • 2017-09-09
  • 1970-01-01
  • 2015-09-25
  • 1970-01-01
相关资源
最近更新 更多