I am trying to retrieve records using Logical grouping in Laravel. I am doing this in API Resource.
What I want?
I want to pass arguments inside API resource function and use that value in where condition. For example: Address::where(function($q1) use (somevalue)
.
What I did
I tried with the following code.
public function toArray($request)
{
return [
'name' => $this->name,
'domain' => $this->domain,
'addresses' => AddressResource::collection(Address::where(function($q1) use ($this->company_id){
$q1->where('company_id', $this->company_id);
})
->where(function($q2) {
$q2->where('is_shipping', 1)
->orWhere('is_billing', 1);
})
->get()),
];
}
But the issue here is that $this->company_id
cannot be passed. It only accepts static values like abc
BUT not as above $this->company_id
.
Error I got
syntax error, unexpected token \"->\", expecting \")\"
at line number 27
(Note: 'addresses' => AddressResource::coll......
is line number 27)
How can I achieve this? any lead would be highly appreciated.
CodePudding user response:
You can try this
public function toArray($request)
{
$company_id = $this->company_id;
return [
'name' => $this->name,
'domain' => $this->domain,
'addresses' => AddressResource::collection(Address::where(function($q1) use ($company_id){
$q1->where('company_id', $company_id);
})
->where(function($q2) {
$q2->where('is_shipping', 1)
->orWhere('is_billing', 1);
})
->get()),
];
}
CodePudding user response:
You can't pass directly. take a Var abc and store your value $abc = $this->company_id; then pass to the closure fucntion. I Hope this will work