Vijayanand Premnath Vijayanand Premnath - 26 days ago 7
PHP Question

Laravel not able to pass userId to the model query

I have two tables one a master table for providers and another a mapping table for provider-user which has mapping ID with additional fields which are user specific.

I get values in return if I have the below code.

return $mobileProviders=Provider::whereHas('providerUser', function ($query) {
$query->where('user_id',1);
})->where('provider_type',1)->get();


Now I pass Auth $userId it does not returns any value When I return $userId I get 1 which is same as the above but I could not get the result.

$userId=Auth::user()->id;
return $mobileProviders=Provider::whereHas('providerUser', function ($query) {
$query->where('user_id',$userId);
})->where('provider_type',1)->get();

Answer Source

Just add a use ($userId) after function ($query). like below:

$userId=Auth::user()->id;

return $mobileProviders = Provider::whereHas('providerUser', function ($query) use ($userId) {
           $query->where('user_id',$userId);
      })->where('provider_type',1)->get();

This will pass the variable to closure.