首页 > 解决方案 > 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;

你能告诉我这是为什么吗?

标签: phplaravel

解决方案


您应该检查 first() 的值是否为空。

  $category = Category::where('name', $request->get('keyword'))->first();
  if($category){
   $category_id = $category->id
  }else{
   //do something if null
  }

与 product_id 相同

希望能帮助到你。


推荐阅读