D
D
Dimon3x2019-01-19 09:45:09
Laravel
Dimon3x, 2019-01-19 09:45:09

How to display posts of different models that have one common tag?

There are image models, videos, tags.
For tags, I used polymorphic links (Many To Many (Polymorphic)) all according to the dock.

class Tag extends Model
{
    public function images()
    {
        return $this->morphedByMany('App\Image', 'taggable');
    }
   
    public function videos()
    {
        return $this->morphedByMany('App\Video', 'taggable');
    }
}

I'm trying to get it out
$tag = Tag::find(1);
       
foreach ($tag->images as $image) {
    dump($image);
}
       
foreach ($tag->videos as $video) {
    dump($video);
}

But I do not like this option, how can I do it in one cycle?
Or output in two loops and merge the collections?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin B., 2019-01-19
@Kostik_1993

You can simply combine the resulting collections into one
. But there will be a nuance in that the methods used in the Image and Video model cycles must be the same

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question