Pexilius's avatar

Paginate user articles

I have a route that displays all the groups of a specific person. But I would like to paginate this.

Currently it's paginating all the groups per user. But I can't seem to simply just get the group. The relationship is many to many (with pivot ect)

What I have at the moment is wrong, but how would I fix this?

public function index()
    {
        $user = Auth::user();
        $groups = Group::orderBy('created_at', 'asc')->paginate(8);
        return view('group.index', compact('groups', 'user'));
    }
@foreach (array_chunk($user->groups->all(), 4) as $row)
<div class="row">
    @foreach ($row as $group)
    <div class="col-md-3">
        <a href="/groups/{{$group->slug}}">
            <div class="group-list btn">
                <div class="panel panel-default">
                    <div class="panel-heading">{{ $group->name }}</div>
                    <div class="panel-body">
                        <img src='{{ $group->groupimage}}' alt='icon-{{ $group->name}}' class='groupicon'>
                        <article><i>"{{ $group->shortdesc}}"</i></article>
                    </div>
                </div>
            </div>
        </a>
    </div>
    @endforeach
</div>
@endforeach 

{!! $groups->render() !!}   

So as you can see, the pagination is done on all the groups at the moment, but how can I simply just retrieve the user's groups?

Thanks

0 likes
3 replies
mstnorris's avatar
Level 55
$user = auth()->user();

$groups = $user->groups()->paginate(8); // sorry I always ALWAYS get confused whether it should be "groups" or "groups()"
Pexilius's avatar

@mstnorris This still doesn't work. I get 2 pages of 16 groups. And they are duplicate. Nvm, it works! Thanks

Francismori7's avatar

@mstnorris Use ->groups when you need the Collection (it runs the query) and use ->groups() when you need the query object (that way you can add a where clause to the query, and then run get()).

Please or to participate in this conversation.