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?

The Only Smart Boy
  • 578
  • 19
  • 39
  • Does this answer your question? [In PHP, what is a closure and why does it use the "use" identifier?](https://stackoverflow.com/questions/1065188/in-php-what-is-a-closure-and-why-does-it-use-the-use-identifier) – Nico Haase Jul 12 '21 at 11:34
  • Or this? https://stackoverflow.com/questions/15042197/access-variables-from-parent-scope-in-anonymous-php-function – Nico Haase Jul 12 '21 at 11:34
  • Or this? https://stackoverflow.com/questions/10692817/whats-the-difference-between-closure-parameters-and-the-use-keyword – Nico Haase Jul 12 '21 at 11:35

1 Answers1

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();
}
Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88