Eloquent Polymorphic Many-to-Many: Practical Example
HTML-код
- Опубликовано: 2 авг 2024
- If you have Tags that may belong to many Posts/Videos/Courses, how to search all records by a specific tag?
Text article version of this video: laraveldaily.com/post/laravel...
- - - - -
Support the channel by checking out my products:
- My Laravel courses: laraveldaily.com/courses
- Laravel QuickAdminPanel: quickadminpanel.com
- Livewire Kit Components: livewirekit.com
- - - - -
Other places to follow:
- My weekly Laravel newsletter: us11.campaign-archive.com/hom...
- My personal Twitter: / povilaskorop Хобби
Found a solution to this by creating a separate Taggable model.
In your Taggable model you can add this.
public function taggable(): MorphTo
{
return $this->morphTo();
}
and in your Tag model you can add this.
public function related(): MorphOne
{
return $this->morphOne(Taggable::class, 'taggable');
}
and now your query would look like this.
$tags = Taggable::with(['taggable'])->get();
$tags->map(function ($tag) {
return [
'id' => $tag->taggable->id,
'title' => $tag->taggable->title
];
});
Looks cool! Another possible solution, yes.
Hi. Instead of map to create same structure we can use appends on model (or with or other idea) also using eager loading method...(?) Will enjoy only on model specification.
Thanks
I don't like to put logic on database.
what about if I don't want to use laravel in future!
I don't think that's professional.
what's your opinion?
does quickadminpanel support this relationship?
No we don't support polymorphic relations, it would be too complex to generate for all possible cases.