php - Laravel“试图获取非对象的属性'id'”
问题描述
我想用资源控制器返回 Laravel 的搜索结果这是我的代码
public function index(Request $request)
{
try {
// Verify the authentication role
if (!$this->hasPermissionTo('read purchases')) {
return $this->sendPermissionError();
}
// Init query
$query = Purchase::query();
// Default order by
$query->orderBy('id', 'DESC');
// Filter by keyword
if ($request->has('keyword')) {
$product_id = Product::where('product_name', $request->get('keyword'))->first()->id;
if(!is_null($product_id)){
$query->where('product_id', '=', "{$product_id}");
$result = $query->paginate(10);
return PurchaseResource::collection($result);
}
$category_id = Category::where('name', $request->get('keyword'))->first()->id;
if(!is_null($category_id)){
$query->orWhere('category_id', '=', "{$category_id}");
$result = $query->paginate(10);
return PurchaseResource::collection($result);
}
}
$result = $query->paginate(10);
// Retrieved execute
//$purchases = Purchase::paginate();
// Return objects
return PurchaseResource::collection($result);
} catch (\Exception $ex) {
return $this->sendError($ex->getMessage());
}
}
我正在搜索产品和类别以及产品,但是当我通过我的错误“尝试获取非对象的属性'id'”来搜索类别时。对于下面的行
$product_id = Product::where('product_name', $request->get('keyword'))->first()->id;
$category_id = Category::where('name', $request->get('keyword'))->first()->id;
你能告诉我这是为什么吗?
解决方案
您应该检查 first() 的值是否为空。
$category = Category::where('name', $request->get('keyword'))->first();
if($category){
$category_id = $category->id
}else{
//do something if null
}
与 product_id 相同
希望能帮助到你。
推荐阅读
- python - 一个请求下载多个文件名?Python
- java - 有没有一种“正确”的方法来避免“必须是最终的”错误?
- python - 在 Python C 扩展中使用来自 PyObjects 的数据而不持有 GIL
- c++ - Constraing template parameter by another template with any specialization type
- python - 从几个大型 Pandas 数据帧中有效地提取一些值
- java - Open telephone number link
- mongodb - 如何在 $project 中将 $toString 用于 MongoDB 上的子文档字段?
- python - 斐波那契数列在 python 中不起作用,解释器崩溃
- java - 用于渲染 2D 和 3D 交互式图形的 Java API(Javaview 替代品)
- c# - 将属性绑定到表达式