how to retrieve nested polymorphic relationship

168 Views Asked by At

in a multilingual app I have these models in my app with polymorphic relations:

  • Post
  • Category
  • Tag
  • Translate

these relations between them:

Post       ->taggable,categorizable,translatable
Category   ->Translatable
Tag        ->Translatable 

this is migrations that I use:

        //categories
        $table->bigIncrements('id');
        $table->string('icon')->nullable();
        $table->integer('parent_id')->unsigned()->nullable();
        $table->timestamps();

        //categorizables
        $table->integer('category_id');
        $table->integer('categorizable_id');
        $table->string('categorizable_type');
        $table->primary(['category_id', 'categorizable_id', 'categorizable_type'],'categorizables');

        //tags
        $table->bigIncrements('id');
        $table->timestamps();

        //taggables
        $table->integer('tag_id');
        $table->integer('taggable_id');
        $table->string('taggable_type');
        $table->primary(['tag_id', 'taggable_id', 'taggable_type'],'taggables');

        //translates
        $table->bigIncrements('id');
        $table->string('lang',10);
        $table->string('title',150)->nullable();
        $table->string('name',50)->nullable();
        $table->string('description')->nullable();
        $table->text('content')->nullable();
        $table->timestamps();

        //translatables
        $table->integer('translate_id');
        $table->integer('translatable_id');
        $table->string('translatable_type');
        $table->primary(['translate_id', 'translatable_id', 'translatable_type'],'translatables');

and I have traits like this to define relations:

trait Translatable{
    public function translates(){
        return $this->morphToMany(Translate::class,'translatable','translatables','translatable_id','translate_id');
    }
}

I tried to get all categories with translations and passed them to a view:

$categories = Category::with('translates')->get();
return view('categories.index', compact('categories'));

in view based on the current locale, I want to get a translation of the category name and I don't know how? I would be appreciated if you can help me solve this.

in the category model I tried to write a function like this to get the current translation:

 public function currentTranslte()
    {
        $locale=app()->getLocale();
        return $this->hasOne(Translate::class,'id')->where('lang',$locale);
    }

but it's not working. in view I want to use something like:

@forelse ($categories as $category)
{{$category->currentTranslate->name}}

 @empty
    <p>
    nothing found
    </p>
@endforelse
1

There are 1 best solutions below

1
On

What about this:

$locale = ...

$categories = Category::with(['translates' => function ($query) use ($locale) {
    $query->where('lang', $locale);
}])->get();

return view('categories.index', compact('categories'));