-1

I have issue with taking data from database based on hasMany relations and send it to api in Larave. Below code, Laravel do not give me product of Customer where Customer id = $id. I don't know why, I can't send $id next to $query. If I write number in '' I have good answear but I need take it automaticly.

$products = Product::where('name', 'like', '%'.$request->q.'%')->orWhere('symbol', 'like', '%'.$request->q.'%')->with(['customers' => function ($query, $id) {
    $query->where('id', '=', $id);
}])->get();

all api code

Route::get('/customer/{id}/products', function(Request $request, $id){
   $customer = Customer::findOrFail($id);
   $products = Product::where('name', 'like', '%'.$request->q.'%')->orWhere('symbol', 'like', '%'.$request->q.'%')->with(['customers' => function ($query, $id) {
       $query->where('id', '=', $id);
   }])->get();

   return $products;
});

Thank you in advance.

diakosavvasn
  • 854
  • 1
  • 8
  • 22
azbroja
  • 95
  • 1
  • 1
  • 12

1 Answers1

2

If you want to use a variable inside the with method, you have to type use($id) after the function($query) like this code below.

$products = Product::where('name','like','%'.$request->q.'%')
    ->orWhere('symbol', 'like', '%'.$request->q.'%')
    ->with(['customers' => function ($query) use($id) {
         $query->where('id', '=', $id);
    }])->get();

If you need to find the product with those Customer's conditions you can use the whereHas function. Check this post for further information.

diakosavvasn
  • 854
  • 1
  • 8
  • 22