Converting a tag to a slug and back

So I use tags in my blog but I want them to look neat in the URL as in:

This - interesting-property
Not this - interesting%2BProperty

For that, I used the slug version so easy enough using $tag->slug()

But here is my issue. If I am searching by the tag I send the slug of the tag in the URL to the controller as …/blog/interesting-property

That gets sent through the controller and at this point:

// Add The Tag Filter
if ($tag = urldecode(param('tag') ?? ''))
{
    $tag_posts = $tag_posts->filterBy('posttags', $tag, ',');
}

And no results are returned. I know why because it is searching for “interesting-property” but as it can only find “Interesting Property” it doesn’t match.

What do I need to do? I believe I need to amend the above code so that it first un-slugs it? Really not sure, but I am sure I am missing something simple…

Use filter with a callback and sluggify the values before comparing.

$tag_posts = $tag_posts->filter( fn($post) => in_array($tag, array_map(fn ($tag) => Str::slug($tag), $post->tags()->split())));

That’s not possible.

1 Like

Thanks Sonja, that works well, just one correction in case anyone sees this, reads it all and gets confused.

$tag_posts = $tag_posts->filter( fn($post) => in_array($tag, array_map(fn ($tag) => Str::slug($tag), $post->posttags()->split())));

At the the end it should be $post->posttags()->split())));

Yeah, I should sort out my naming convention on things!