0

I have colors request in array $colors = collect($request->colors);

i am trying when query builder for make request when its not empty

$products = Product::when($colors, function ($query, $colors) {
   return $query->whereHas('colors', function (Builder $query) use ($colors) {
     $query->whereIn('slug',  $colors->toArray());
    });
 })

it should not be trigger color query

when i try

when(!$colors->isEmpty(), function ($query, $colors)

its trigger when there is array data in colors request but inside query its return boolean instead of original array data

help!

3
  • The first parameter will always be the one to be evaluated as true or false, so if you do !$colors->isEmpty() that transforms automatically into a boolean and that is what $colors will be, so you have to use first code, not second. So, what is your problem with the first one ? Commented Jul 10, 2021 at 22:10
  • @matiaslauriti the problem with the first one is that an object is always true Commented Jul 10, 2021 at 22:18
  • 1
    One solution is as the user @lagbox shared (the best one), other solution but really not clean is do this: $colors->isNotEmpty() ? $colors : false. Commented Jul 10, 2021 at 23:26

1 Answer 1

2

If you really want to use the when method there with that Collection you can scope in the $colors variable:

Product::when($colors->isNotEmpty(), function ($query) use ($colors) {
    ...
})...
Sign up to request clarification or add additional context in comments.

1 Comment

$colors->isNotEmpty() ? $colors : false this fix my code

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.