You can do it like this
$query = static::select(['brand', 'color', 'size'])
->where([
['stock', 'in-stock'],
['brand', '!=', ''],
['color', '!=', ''],
]);
if($request->categoryTitle)->filled()) {
$query->where(function ($query) use ($categoryTitle) {
foreach ($categoryTitle as $item) {
$query->orWhere('category_title', $item);
}
});
if($request->attrBrand)->filled()) {
$query->where(function ($query) use ($attrBrand) {
foreach ($attrBrand as $id => $item) {
$query->orWhere('brand', $item->title);
}
});
if($request->attrColor)->filled()) {
$query->where(function ($query) use ($attrColor) {
foreach ($attrColor as $id => $item) {
$query->orWhere('color', $item->title);
}
})
return $query->get();
So, building up the query if filters are set.
What @tykus is saying is that there is a when method that does the same but allows it to be constructed as one fluent eloquent statement;
return static::select(['brand', 'color', 'size'])
->where([
['stock', 'in-stock'],
['brand', '!=', ''],
['color', '!=', ''],
])
->when($request->categoryTitle)->filled()) {
$query->where(function ($query) use ($categoryTitle) {
foreach ($categoryTitle as $item) {
$query->orWhere('category_title', $item);
}
})
->when($request->attrBrand)->filled()) {
$query->where(function ($query) use ($attrBrand) {
foreach ($attrBrand as $id => $item) {
$query->orWhere('brand', $item->title);
}
})
->when($request->attrColor)->filled()) {
$query->where(function ($query) use ($attrColor) {
foreach ($attrColor as $id => $item) {
$query->orWhere('color', $item->title);
}
})
->get()
Note I notice your filters look off? item on category and item->name on the others? What does your form return as filters? Surely just an array of selected filters or checkboxes?