cviebrock / eloquent-sluggable

Easy creation of slugs for your Eloquent models in Laravel
MIT License
3.91k stars 461 forks source link

Advice on conditional slug uniqueness #612

Closed Stantastic closed 5 months ago

Stantastic commented 5 months ago

My Doumentation model has a column parent_id with a default value of 0. A model instance can be either a 'Documentation' or 'Documentation Page' by setting the parent_id.

Now my actual issue:

I only want slugs to be unique where slugs in my model are unique within the same parent_id to later on get a specific documentation and its page from the url.

The indented behaviour would look like this: Docs A - Slug: page-a Page - Slug: page Page - Slug: page-2

Docs B - Slug: page-b Page - Slug: page Page - Slug: page-2

Docs B - Slug: page-b-2 Page - Slug: page Page - Slug: page-2

cviebrock commented 5 months ago

If I understand correctly, this should be what you want: https://github.com/cviebrock/eloquent-sluggable?tab=readme-ov-file#scopewithuniqueslugconstraints

Stantastic commented 5 months ago

Thanks for the advice! I must've missed that in the docs. I was able to achieve the desired result with:


    * Scope to apply unique constraints for slugs based on assigned parent.
    */
    public function scopeWithUniqueSlugConstraints($query)
    {
        if ($this->parent_id == 0) {
            return $query->where('parent_id', 0);
        }
        return $query->where('parent_id', $this->parent_id);
    }```
cviebrock commented 5 months ago

You could also just remove that if {…} block entirely and get the same result. 😉

public function scopeWithUniqueSlugConstraints($query)
{
    return $query->where('parent_id', $this->parent_id);
}