Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving all morphedByMany relations in Laravel Eloquent

Tags:

In the Laravel documentation, there is the following example for retrieving morphedByMany relations, which are many-to-many polymorphic relations.

Laravel Many to Many polymorphic relations documentation

namespace App;  use Illuminate\Database\Eloquent\Model;  class Tag extends Model {     /**      * Get all of the posts that are assigned this tag.     */     public function posts()     {         return $this->morphedByMany('App\Post', 'taggable');     }      /**      * Get all of the videos that are assigned this tag.      */     public function videos()     {         return $this->morphedByMany('App\Video', 'taggable');     } } 

How would I get a list of all morphed relations in one query / collection, for instance, posts and videos, and then if I later added photos (or anything), that too?

like image 898
Andrew Willis Avatar asked Mar 11 '16 19:03

Andrew Willis


2 Answers

I use a trick here:

Create a Model Taggable for your connection table taggable and add a hasMany relation to the Tag model.

public function related() {     return $this->hasMany(Taggable::class); } 

Within your Taggable model create a morphedTo relation.

public function taggables() {     return $this->morphTo(); } 

Now you can get all models which are using the tag by calling:

$tagged = Tag::with('related.taggables'); 
like image 141
iPaat Avatar answered Sep 27 '22 21:09

iPaat


Did you think to use the "union" function of the collections to merge all the different collection in order to retrieve all what you need?

class Tag extends Model {     [...]      /**      * Get all of.      */     public function morphed()     {         return $this->video->union($this->posts)->all();     } } 
like image 41
Simone Cabrino Avatar answered Sep 27 '22 21:09

Simone Cabrino