3

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

Emmanuel-Ab
  • 321
  • 2
  • 15
  • `$chart = Trending::with('trendingable')->get();` I haven't used morph relationships, but can you do this and show me whether it gives all data with `trendingable` ? – Akhtar Munir Jun 04 '20 at 06:03

1 Answers1

1

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

OMR
  • 11,736
  • 5
  • 20
  • 35