I want to filter the data with array, but return null if one of element in array is false.
for example my existing cars color is ['black', 'white', 'red']
I already try with whereIn but in the docs say given containing value within the given array thats why it's still return the data.
In my controller:
// the request param is /cars?color=black,white,yellow
$cars = Car::latest()->filter(request(['color', ...etc]))->get();
// $cars should empty
// the request param is /cars?color=black,white,red
$cars = Car::latest()->filter(request(['color', ...etc]))->get();
// $cars shouldn't empty
In my model:
public function colors() {
return $this->hasMany(Color::class);
}
public function scopeFilter($query, array $filters) {
$query->when($filters['color'] ?? false, function ($query, $colors) {
$colors = explode(',', $color);
$query->whereHas('colors', function ($q) use ($color) {
$q->whereIn('color_name', $colors);
});
});
}