1

I have the code bellow aimed at retrieving all the service providers using the service ID

 public function getProvidersByPackage($id = null){ $package_id = $id; $providers = ServiceProvider::whereHas('services', function($query) { $query->where('packages.id', 1); })->get(); dd($providers); } 

I would like to replace the constant 1 with the variable $id passed to the outer function getProvidersByPackage() my problem is that when I try the following

 public function getProvidersByPackage($id = null){ $package_id = $id; $providers = ServiceProvider::whereHas('services', function($query) { $query->where('packages.id', $id); })->get(); dd($providers); } 

I get the error $id is not defined and when I try

 public function getProvidersByPackage($id = null){ $package_id = $id; $providers = ServiceProvider::whereHas('services', function(&$package_id, $query) { $query->where('package.package_id', $package_id); })->get(); } 

I get the ArgumentCountError bellow

 Too few arguments to function App\Http\Controllers\ShopController::App\Http\Controllers\{closure}(), 1 passed in /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 1207 and exactly 2 expected 

What could I be doing wrong?

3

1 Answer 1

1

In PHP, you can pass a variable to a closure using the use syntax

public function getProvidersByPackage($id = null) { $package_id = $id; $providers = ServiceProvider::whereHas('services', function ($query) use ($package_id) { $query->where('package.package_id', $package_id); })->get(); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.