Search code examples
phplaraveleloquentslug

eloquent-sluggable uniqueness test by relationship id


I try to use cviebrock/eloquent-sluggable in Laravel (5.4). I have a Page model and a website model. It's using sluggable in the Page model. Now, if i create a page i want tot check for uniqueness by the columns website_id and slug before generating a slug (with -1 or -2 after the title for example). It looks like i should use the method "customizeSlugEngine", but it isn't called when i add it to the Page model.

When it's working i need to find page by slug and page id. In my pageController (front-end) i use:

Page::findBySlug($slug);

How can i find pages by slug and webiste_id?


Solution

  • Thanks for the comments and answers.

    First, i was making a mistake in the first part of my question. I did a custom validation in Laravel on a unique slug, without website id. I changed this and it's works fine.

    'slug' => 'unique:pages,slug,NULL,pages,website_id,'.\Request::get('website_id'),
    

    The model needs the function "scopeWithUniqueSlugConstraints" to check for multiple columns before generating.

    public function website()
    {
        return $this->belongsTo('App\Models\Website');
    }
    
    public function scopeWithUniqueSlugConstraints(Builder $query, Model $model, $attribute, $config, $slug)
    {
        $website = $model->website;
        return $query->where('website_id', $website->getKey());
    }
    

    In my pageController (front-end) I call the page with:

    Page::whereSlug($slug)->where('website_id', '=', $website_id)->first();