cviebrock / eloquent-sluggable

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

Polymorphic One-to-One (Question) #581

Closed rezaffm closed 2 years ago

rezaffm commented 2 years ago

Hello,

I have a polymorphic model called "entry", like:

        Schema::create('entries', function (Blueprint $table) {
            $table->id();
            $table->string('title')->nullable();
            $table->string('slug')->nullable()->index();
            ....
            $table->morphs('entryable');
        });

which is used for Posts, Pages, Reviews et cetera, for example:

        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('locale')->index();
        });
        Schema::create('reviews', function (Blueprint $table) {
            $table->id();
            $table->string('locale')->index();
            $table->unsignedBigInteger('co_product_id')->index();

            $table->foreign('co_product_id')->references('id')->on('co_products')->onDelete('cascade');
        });

(using polymorphism to achieve Multitable Inhertiance).

As you can see, the "locale" lives on Posts, Reviews et cetera.

What now gives me a hard time is, how to set up scopeWithUniqueSlugConstraints, because it needs to be dependent upon the entryable_type and locale, which however lives on $model->entrayable, which sometimes it a post, a review ot something else.

How to correctly set it up in this case?

It is relevant for cases, where you have a review on a product, for instance "Apple Iphone", that should be reviewed in English and let's say in German. Therefore, the generated slug should be the same in both languages.

Any help would be greatly appreciated.

rezaffm commented 2 years ago

I am not 100% sure if that did the trick, but it doesn't look too bad either, can you please advise?

    public function scopeWithUniqueSlugConstraints(Builder $query, Model $model, $attribute, $config, $slug)
    {
        return $query
            ->where('entryable_type', $model->entryable_type)
            ->whereHas('entryable', function($query) use ($model) {
                $query->where('locale', $model->entryable->locale);
            });
    }