Laravel - Relationships - Many To Many Polymorphic Retrieving The Relationship
Once your database table and models are defined, you may access the relationships via your models. For example, to access all of the tags for a post, you may use the tags
dynamic relationship property:
use App\Models\Post;
$post = Post::find(1);
foreach ($post->tags as $tag) {
//
}
You may retrieve the parent of a polymorphic relation from the polymorphic child model by accessing the name of the method that performs the call to morphedByMany
. In this case, that is the posts
or videos
methods on the Tag
model:
use App\Models\Tag;
$tag = Tag::find(1);
foreach ($tag->posts as $post) {
//
}
foreach ($tag->videos as $video) {
//
}