Resurrecting this thread because I have run into a similar issue while building a cookbook.
I have several different types of params and can easily filter between those. However, when I want to combine multiple instances of the same param, I am not sure how to properly filter my collection.
Here is my controller:
<?php
return function ($site, $page) {
$recipes = collection('recipes');
/* FILTERS */
$diets = Str::split(param('diet'), ',');
$type = param('type');
$author = param('author');
$random = param('random');
$query = get('q'); // Search
$recipesFiltered = $recipes
->when(($diets), function ($diets) {
return $this->filterBy('diet', 'in', $diets, ', ');
})
->when($type, function ($type) {
return $this->filterBy('type', $type, ',');
})
->when($author, function ($author) {
return $this->filterBy('author', "- $author");
})
->when($random, function ($random) {
return $this->shuffle()->limit($random);
})
->when($query, function ($query) {
return $this->search($query, 'title|ingredients|diet');
});
return [
'query' => $query,
'recipes' => $recipes,
'recipesFiltered' => $recipesFiltered
];
};
All except for the $diets
param are single-select, so no problem there. However, I want to be able to combine different types of diet and filter the recipes accordingly. I therefor split the param into an array and then filter the recipes by that array. The problem is that this matches recipes that fit any of the items in the array and not all of them.
So if I have 10 vegan and 15 vegetarian recipes and I filter for “vegan, vegetarian” it should return only 10, not 15 recipes.
As @texnixe suggested in her last comment, I should probably use the filter
method instead but I haven’t been able to get this working. I tried turning the diet-information of the individual recipe into an array (it’s saved via checkboxes) and I guess I could somehow compare that to my params array?!
I am a bit lost but if someone would be able to point me in the right direction, I’d really appreciate it.