首页 > 解决方案 > How to get one single value from an SQL request in Laravel?

问题描述

I'm trying to display all the Products whose Category matches the $id I'm getting by clicking a specific Category.

I tried using the ->first() and ->pluck('name') functions

I tried doing this in the CategoriesController :

public function show($id)
    {
        $category = Category::where('id', $id)->pluck('name');
        $products = Product::where('categorie', $category)->get();
        return view('categories.show')->with('products',$products);
    }

ErrorException Method links does not exist. (View: C:\wamp64\www\gestionPointDeVente\resources\views\categories\show.blade.php) (which is the page that displays all the products of that category)

BadMethodCallException Method links does not exist. in Macroable.php line 74

Thanks a lot !

标签: phpsqllaravel

解决方案


首先对于类别,您可以使用路由模型绑定,因此:

public function show($id)

可以变成这样:

public function show(Category $category)
{
    // if you decide to keep the id you can uncomment the next line
    // $category = Category::find($id);

    // the product has the category name or id? 
    $products = Product::where('categorie', $category->name)->get();
    return view('categories.show')->with('products',$products);
}

然后错误说links如果您使用分页,您缺少一个存在的方法,但在您的代码中您没有。

所以这一行:

$products = Product::where('categorie', $category->name)->get();

应该变成这样:

$products = Product::where('categorie', $category->name)->paginate(10);

推荐阅读