Filterby with a variable

Hello,

I would like to dynamically display different values for each page. For this to work, I would like to ‘filterby’ pages which contain the same string as a given variable. I would like to do something like this:

$results = $pages->find('magazines')->children()->visible()->filterBy('year', '*=', '$chosenyear')

Obviously, this doesn’t work like this with the “$chosenyear” variable in it. What is the best workaround for that? Thank you very much for your help :slightly_smiling:

Why does this not work? Is chosenyear a field of all your pages, or where does its value come from?

Assuming chosenyear and year are both fields of all of the pages you want to filter, you can use the filter method that accepts a callback:

$results = $pages->find('magazines')->children()->visible()->filter(function ($child) {
    return str::contains($child->year()-value(), $child->chosenyear()->value());
});

The callback that you pass to the filter method has to return a boolean value for each element of the collection that determines whether it should be in the result or not.

Sorry. I think, I did a bad job in explaining.

An example of the structure of the site is this: /genre/magazine-title/issue-title/issue.txt

Every issue has a year value.

I now want to create pages to list all issues of all magazines across all genres that have a specific ‘year’ value. For example to list all issues that have “1988” as year value. Every page has the chosenyear value of the year that I want to be listed.

Maybe I’m thinking way to complicated and there is a much easier solution than what I’m thinking of?

If I get this right, the problem is not the filter, but filtering the right collection of pages. The issues you want to filter seem to be more deeply nested than $pages->find('magazines')->children()?

Yeah, I’m using grandChildren(). And everything works fine if I manually input the year instead of “$chosenyear”. So I’m just looking how to implement the variable in there.

Of what type is $chosenyear?

You’ve got '$chosenyear' in single quotes in your code example. Try it without the quotes.

3 Likes

Oh yes, of course, I completely overlooked that :blush:

… Ok, that’s just pretty embarrassing … Thank you! :grin: