Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

acoustic85's avatar

Search api

Hi Everyone,

I am trying to make api for searching products by NAME and PRICE but for some reason im getting error "Property [id] does not exist on this collection instance."

This is my route
Route::get('product/search', [SearchController::class, 'search']);


and this is my controller


    public function search(Request $request) {


        $search = request()->get('search');
        $price = request()->get('price');


      $product = Product::where('name', 'LIKE', "%{$search}%")
                 ->orWhere('price', 'LIKE', "%{$price}%" )->get();

      if ($product) {
        return $this->handleResponse(new ProductResource($product), 'Product Retrieved.' );

       }

       return $this->handleError('Product not found');

     }


0 likes
5 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

So you want 1 product or multiple? I assume multiple

      $products = Product::where('name', 'LIKE', "%{$search}%")
                 ->orWhere('price', 'LIKE', "%{$price}%" )->get();
      if ($products->isNotEmpty()) {
        return $this->handleResponse(ProductResource::collection($product), 'Products Retrieved.' );

       }

If you only expect 1 product

      $product = Product::where('name', 'LIKE', "%{$search}%")
                 ->orWhere('price', 'LIKE', "%{$price}%" )->first(); //get the first()

      if ($product) {
        return $this->handleResponse(new ProductResource($product), 'Product Retrieved.' );

       }
acoustic85's avatar

thanks for your answer. The error is gone now but whatever i type now all the products are coming

Sinnbeck's avatar

@doncho85 I would need to see the code that does the query. And it might be a good idea, to check if it actually adds the query parameters like you expect. In the browser hit F12, and select Network. Now do the request, and see the url that shows up. Does it have ?search=something ?

Sinnbeck's avatar

@doncho85 Ok sounds good. If its solved, you can close the thread by marking a best answer

Please or to participate in this conversation.