Filtrer blog posts using variable

I created variable in layout
{variable name=“blogcategory” tab=“Tab” label=“Label” type=“text”}{/variable}

I wanted do filter blog posts with this variable but it doesnt work

{% set posts = blogPosts.posts.whereRelation(‘category’, blogcategory).get() %}

Hey @mkinternet

The blogPosts.posts property in Twig is already a Collection, not a query builder, so Eloquent methods like whereRelation() and get() won’t work there.

The simplest solution is to use the component’s built-in category filter. In your page/layout where you define the component:

[blogPosts]
categoryFilter = "{{ :blogcategory }}"

This tells the Blog Posts component to filter by category before the query runs, and it will respect pagination too.

If you need to filter after the fact in Twig, you can use the filter function on the collection:

{% set filtered = blogPosts.posts|filter(post => post.categories.contains('slug', blogcategory)) %}

But the component filter (Option 1) is the better approach since it filters at the database level.

1 Like