Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

webdotapp's avatar

Laravel Eloquent for recents rows from three table

Hello,

I am stuck with following, i have following schema...

users: id, name, password
blogs: id, user_id, title
posts: id, blog_id, post

I want to list recent 5 posts for authenticated user, i am able to do this using Query Builder, but how can i do this using eloquent in simple way, please assist, thanks

0 likes
2 replies
jhoff's avatar
jhoff
Best Answer
Level 14

This is almost verbatim the example in the docs for hasManyThrough: http://laravel.com/docs/5.1/eloquent-relationships#has-many-through

I would setup a posts relationship and then grab the 5 most recent as needed

App\User.php

...
    protected function posts()
    {
        return $this->hasManyThrough( 'App\Post', 'App\Blog' );
    }

    protected function recentPosts( $count )
    {
        return $this->posts()->latest()->take( $count )->get();
    }
...

Then to grab the 5 most recent

    Auth::user()->recentPosts(5);
1 like

Please or to participate in this conversation.