【问题标题】:My controller considers that my store id is the products id我的控制器认为我的商店 id 是产品 id
【发布时间】:2019-01-31 19:15:44
【问题描述】:

我的控制器无法读取“样本”是商店而不是产品。 我的 web.php 上有这条路线

    Route::get('{store}/products/{products}/edit', [
    'as'    => 'store.products.edit',
    'uses'  => 'ProductsController@edit',
    function($store) {
        $store = App\Models\Store::where('slug', $store)->firstOrFail();
    }
]);

这是我的 ProductsController@edit

    public function edit($id)
{
    $product = Product::findOrFail($id);

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

当我运行网址时:http://127.0.0.1:8000/sample/products/022fe902-7f4d-4db1-b562-04a7eb9f5a68/edit

其中 sample 是 {store},022fe902-7f4d-4db1-b562-04a7eb9f5a68 是 {product}

我收到此错误:

没有模型 [App\Models\Product] 示例的查询结果

在我的查询中:

select * from products where products.uuid = 'sample' limit 1

【问题讨论】:

    标签: php laravel laravel-5 laravel-routing


    【解决方案1】:

    如果你有 2 个参数,你应该在你的控制器中都以有效的顺序,所以你应该有:

    public function edit($store, $id)
    {
        $product = Product::findOrFail($id);
    
        return view('view here', compact('product'));
    }
    

    这里也可能你不需要:

    function($store) {
       $store = App\Models\Store::where('slug', $store)->firstOrFail();
    }
    

    对于任何事情,但也许在你的控制器中你应该做这样的事情:

    $store = App\Models\Store::where('slug', $store)->firstOrFail();
    $product = $store->products()->findOrFail($id);
    

    假设您在这家商店有产品,并且您想确保有人不会编辑分配给不同商店的产品。

    【讨论】:

    • 谢谢!正是我需要的
    猜你喜欢
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2015-06-16
    • 1970-01-01
    相关资源
    最近更新 更多