php - 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 !
解决方案
首先对于类别,您可以使用路由模型绑定,因此:
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);
推荐阅读
- javascript - 更改 AWS cognito 登录 UI 中的文本
- javascript - 如何从在 AJAX 中创建的表中获取“innerText”内的项目总和?
- c# - 尝试从过程中获取数据时:PL/SQL - 数字或值错误
- css - 引导行大纲
- c++ - 为链接列表中的函数设置参数
- python - 在数据框中搜索同一对(Python)
- c# - 如何使用自定义错误模型返回 BadRequest 响应?网页 API 2
- python - 在没有熊猫的情况下将 sqlalchemy 对象返回到数据库表的最佳方法是什么?
- sql - 获取参考表行的总和
- c++ - Adding a type to an existing template with out it being dropped c++17