You just have to put the loop inside the closure (the function with the $subQuery). And since inside the closure PHP doesn't know the $accountTypes variable you need to have a use statement in the closure too.
$query->where(function ($subQuery) use ($accountTypes) {
foreach ($accountTypes as $accountType) {
$subQuery->orWhere('account_type', $accountType);
}
}
Haven't tested it but that should point you in the right direction :)
Thanks ftiersch. That looks like it'll work. I'll know for sure once I test it.
So I finally tested this and it seems it doesn't work. I'm guessing the subquery considers the $accountTypes variable as a new variable because I get the error "Invalid argument supplied for foreach()".
Anyone know how to solve this?
/bump
This is my full function.
/**
* Fetch dealer id from the database
*
* @param $dealerIdInFeed
* @param $accountTypes
* @return mixed
*/
public function fetchDealerId($dealerIdInFeed, $accountTypes)
{
$dealer = $this->dealer->where('foreign_dealer_id', $dealerIdInFeed)
->where(function ($subQuery) use ($accountTypes) {
foreach($accountTypes as $accountType)
{
$subQuery->orWhere('account_type', $accountType);
}
})
->get();
return $dealer->id;
}
I figured out the problem. There are instances when the array passed to the function only has 1 item in it. Updated function below:
public function fetchDealerId($dealerIdInFeed, $accountTypes)
{
$dealer = $this->dealer->where('foreign_dealer_id', $dealerIdInFeed)
->where(function ($subQuery) use ($accountTypes) {
if(count($accountTypes) > 1)
{
foreach($accountTypes as $accountType)
{
$subQuery->orWhere('account_type', $accountType);
}
}
else
{
$subQuery->orWhere('account_type', $accountTypes);
}
})
->first();
if($dealer != null)
return $dealer->id;
return null;
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community