Get latest entries/posts from categories on many to many relationship Laravel

6 days ago 3
ARTICLE AD BOX

I have a small laravel project with posts and categories and a many to many relationship

public function post_categories(): BelongsToMany { return $this->belongsToMany(PostCategory::class); } public function posts(): BelongsToMany { return $this->belongsToMany(Post::class); }

In my index view, I would like to show the latest post of each category on the left, and the latest 3 posts on the right but I have no idea how to do that.

I tried different things but nothing worked.

The only thing that worked was

$posts_1 = PostCategory::with('posts')->where('id', '=', '1')->first(); $posts_2 = PostCategory::with('posts')->where('id', '=', '2')->first(); $posts_3 = PostCategory::with('posts')->where('id', '=', '3')->first(); ....

I'm sure it's a very ugly way to do things and I would be stucked if I had to create new categories in the futur.

Any help would be much appreciated.

Thanks

Read Entire Article