0

I have saved ids of product categories as a string separated by comma's (e.g. '2,3,4,6') and I have an array of chosen categories by a user (e.g. [1,3,4,5]), I would like to get from a database using eloquent only these products which have selected category. In the example case would be products which contain id 1 or 3 or 4 or 5.

I tried to do it in many variations, but I think that I am slowly getting to the point, but with one issue. I do something like that:

Products::where(function ($query) use ($filters) {
      $categories = implode(',', $filters['categories']); // gives me string with separated ids by comma same as in DB
      $query->where('categories', 'like', "%{$categories}%");
    });

But it takes items with logical "AND". I mean if I select more than 1 category it expects that product has both selected categories instead I would like to get all products which have at least one of the selected categories

piotrruss
  • 417
  • 3
  • 11

1 Answers1

1

Use Wherein here

for example-

$category = [1,2,3,4,5];
$query->WhereIn('categories', $category); // use this
  • I tried it and it seems like it doesn't always work. So I abandon it, but maybe it was my fault so I will check one more time. – piotrruss Feb 08 '19 at 13:16
  • if any of the ids it found, it should work. if not it will not work – Sanjit Bhardwaj Feb 08 '19 at 13:17
  • No, It doesn't work for me. I have few records which contain id = 3 (e.g. '1,2,3', '3,4'). So my filters looked that: $category = [3]; And It returned me empty array instead of 5 results. – piotrruss Feb 08 '19 at 13:20
  • WhereIn simply doesn't work for me when searchable id is not in the first place of a string – piotrruss Feb 08 '19 at 13:23