Reputation: 2984
I am attempting to use the following
$orders = \App\Order::with([
'Customer' => function ($query) use ($filterFirst, $filterLast, $filterstate)
{
if($filterFirst)
{
$query->where('customers.first', 'LIKE', "{$filterFirst}%");
}
if($filterLast)
{
$query->where('customers.last', 'LIKE', "{$filterLast}%");
}
if ($filterstate)
{
$query->where('customers.state', '=', $filterstate);
}
},
'Group' => function ($query) use ($filtercategory)
{
if($filtercategory)
{
$query->where('order_groups.groupid', '=', $filtercategory);
}
},
'Group.ProductGroups' => function ($query) use ($filteractualcat)
{
if($filteractualcat)
{
$query->where('productgroups.cat', '=', $filteractualcat);
}
},
'Group.ProductGroups.Category',
'Doctor',
'Status' => function ($query) use ($filterstatus)
{
if ($filterstatus)
{
$query->whereIn('statuses.id', $filterstatus);
}
},
'Signed'
])->where(function ($query) use ($id, $filterlab, $filterStart, $filterEnd, $filterRep) {
if ($id)
{
$query->where('orders.id', $id);
}
if ($filterlab)
{
$query->where('orders.labid', $filterlab);
}
if ($filterStart || $filterEnd)
{
if ($filterStart && $filterEnd)
{
$query->whereBetween('orders.created_at', [$filterStart, $filterEnd]);
}
else
{
if ($filterStart && !$filterEnd)
{
$query->where('orders.created_at', '>=', $filterStart);
}
else
{
$query->where('orders.created_at', '<=', $filterEnd);
}
}
}
if ($filterRep)
{
$query->where('salesrep', $filterRep);
}
})->orderBy('orders.created_at', 'ASC');
However, when I run ->get
on $orders
I get the entire table of orders, and I just want to get the orders that match the Filters...
Any ideas on how I can accomplish this?
Upvotes: 1
Views: 56
Reputation: 163758
Use whereHas()
to filter orders by customer filters:
$orders = \App\Order::whereHas('Customer', function ($query) use ($filterFirst, $filterLast, $filterstate) {
if ($filterFirst) {
$query->where('first', 'like', $filterFirst . '%');
}
if ($filterLast) {
$query->where('last', 'like', $filterLast . '%');
}
if ($filterstate) {
$query->where('state', $filterstate);
}
})
->get();
If you also want to load customers for orders, add with
to the query.
Upvotes: 1