Query with eloquent amount and limit to obtain


Hello, someone could help me with an eloquent query.

User::with(['post','Y aun tengo más relaciones. ..'])

This way I get the information of a user X and I see the posts.

but I need only show the last 5 post he did. I could use OrderBy and take

But I need to know The total amount of post that user has. could use Count()

I could do it by doing a different query, but I know there's a better way to do it.

I could do it like that. . but there are many consultations, because it is not only that. There are more things that I need to do.


And I know that maybe there is a better way to do it, by the end I will send it to a component vue

asked by Alex Burke Cooper 30.10.2018 в 02:58

1 answer


You can do it in a super simple way using the withCount() method typical of relationships . Check the documentation regarding this section.


Count related models


If you want to count the number of results of a relationship without having   to load the whole relationship itself, you can use the method    withCount , which will place a column called {relation}_count   in your resulting models. For example:

$posts = App\Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo $post->comments_count;

Then, applying this to your query:

    $user = App\Post::withCount('posts')
        ->with(['relacion_1', 'relacion_2', 'posts' => function ($query) {
            $query->ordeBy("id", "desc")->limit(5);
        ->where('nick', $nick)

Then in your view (?) you can access this new attribute like this:

<p> El usuario tiene {{ $user->posts_count }} publicaciones en total </p>

In addition to being able to access the rest of your relationships, including posts , as you would regularly do.

answered by 30.10.2018 в 17:36