Convert laravel morph collection to model collection?

Viewed 298

I have 3 models:

Post, Like, Trending

The like and trending models are polymorphs, both are:

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

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

When I populate the trendings table based on the likes the only way to access the "posts" from a trending collection is to make a foreach loop like this:

$chart = Trending::all();

foreach($chart as $chartItem)
{
   $chartItem->trendingable->title
}

How can I convert the $chart collection into posts collection without the foreach loop? I am using Laravel 5.8

1 Answers

you should always define the opposite of the relation:

public Post extends Model
{
public function trendings()
{
return $this->morphMany('App\Trending', 'trendingable');
}
} 

now if you want to get all posts that have trendings with their trendings:

$postWithTrending=Post::with('trendings')->whereHas('trendings')->get();

if you had to get them by Trending model:

$chart = Trending::where('trendingable_model','=',Post::class)->with
('trendingable')->get()->pluck('trendingable');

but that won't get a list of posts model but array represent posts as key value pairs

Related