Laravel 4.1: proper way to retrieve all morphedBy relations? Laravel 4.1: proper way to retrieve all morphedBy relations? laravel laravel

Laravel 4.1: proper way to retrieve all morphedBy relations?


Was able to figure it out, would love to hear comments on this implementation.

in Tag.php

public function taggable(){    return $this->morphToMany('Tag', 'taggable', 'taggables', 'tag_id')->orWhereRaw('taggables.taggable_type IS NOT NULL');}

in calling code:

$allItemsHavingThisTag = $tag->taggable()                ->with('videos')                ->with('posts')                ->get();


I just used this on Laravel 5.2 (not sure if it is a good strategy though):

Tag model:

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

Taggable model:

public function model(){    return $this->belongsTo( $this->taggable_type, 'taggable_id');}

To retrieve all the inverse relations (all the entities attached to the requested tag):

@foreach ($tag->related as $related)    {{ $related->model }}@endforeach

... sadly this technique doesn't offer eager load functionalities and feels like a hack. At least it makes it simple to check the related model class and show the desired model attributes without much fear to look for the right attributes on the right model.

I posted a similar question in this other thread as I am looking for relations not known in advance.