cviebrock / eloquent-sluggable

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

Advice on conditional slug uniqueness #612

Closed Stantastic closed 4 months ago

Stantastic commented 4 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 4 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 4 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 4 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);
}