Laravel cviebrock/eloquent-sluggable scoped to other objects

39 Views Asked by At

I have a Laravel project that uses this package to create slugs from friendly URLs - https://github.com/cviebrock/eloquent-sluggable

By all research I've done, I know that I can make them unique and the package will automatically handle it by creating slugs like:

new-page
new-page-2
new-page-3

My hangup is this. I want the uniqueness of the slugs to be scoped to other objects. For example, I have a user and their URL is this /john-smith. The user has many albums and each album (with this package generating slugs for the albums) would be something like:

/john-smith/albums/new-thing

And a possible duplicate would generate something like:

/john-smith/albums/new-thing-2

Now, if another user wanted to create an album called New Thing as well, then with the standard setup of this package, it would generate a URL like:

/jane-smith/albums/new-thing-3

Instead of something like a more desired:

/jane-smith/albums/new-thing

I think I understand why this is. I'm sure it has something to do with the model binding going on and it can't bind the album slug if it's not unique across the system.

Anyone know of a way with this package, or even a different package, to accomplish something like this?

1

There are 1 best solutions below

0
ryanpitts1 On

Thanks to @ceejayoz for making me go back and re-read the docs. I didn't fully understand it the first time but I also was able to find another practical example of it and that helped me out!

The fix was to add something like this in the model class:

public function scopeWithUniqueSlugConstraints(Builder $query, Model $model, $attribute, $config, $slug)
{
    $user = $model->user;
    return $query->where('user_id', $user->getKey());
}

This generated slugs that were unique to the user. Still testing things but it appears to be just what I needed.