0

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);
        });
    });
}
2
  • 1
    please update your code also so that we can help ;) Commented Aug 4, 2022 at 6:02
  • What have you tried? edit and post your code Commented Aug 4, 2022 at 6:08

2 Answers 2

1

It sounds like you want a where condition for each selected colour:

$cars = Car::whereHas('colors', function($q) use ($filter) {
    foreach ($filter as $color) {
        $q->where('color_name', $color);
    }
})->get();
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, this looks right.
thanks for answer it, but it works when the filter array has 1 element, if more than element doesn't work
@TutiHerwiyati Because? What is the expected behaviour if there are no colours filtered? Seems like then you'd just get all cars that have at least one colour?
0

Laravel has the function whereIn Documentation here

$filter = ['black', 'white', 'yellow'];
$cars = Car::whereIn('color_name', $filter)->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.