pranath's avatar

Pagination with whereNotIn

Hi,

I have the following code in my UserRolesController and it works perfectly without pagination.

    public function index()
    {
        $users = User::all()->whereNotIn('email','[email protected]')->sortByDesc('created_at');
        return view('users.index', compact('users'));
    }

I would like to paginate the results while maintaining the same condition (i.e not showing the record where 'email' is '[email protected]').

The following code obviously throws the error "Method Illuminate\Database\Eloquent\Collection::paginate does not exist."

$users = User::all()->whereNotIn('email','[email protected]')->sortByDesc('created_at')->paginate(5);

P.S: I have already added <div class="pull-right">{{ $users->links() }}</div> at the bottom of the table in the view.

Your help is highly appreciated :)

0 likes
4 replies
staudenmeir's avatar

You are currently fetching all users and then filtering & sorting them with Collection methods.

Use their query equivalents:

$users = User::whereNotIn('email','[email protected]')->orderByDesc('created_at')->paginate(5);
pranath's avatar

@staudenmeir

I tried your solution and then I again tried by modifying the orderByDesc('created_at') to orderBy('created_at', 'desc').

But still it gives me the following error.

Invalid argument supplied for foreach()

I use a foreach loop to display the records inside a table in the view.

pranath's avatar

Thank you for trying to help me mate!

I actually managed to achieve the same requirement in a different approach. My initial requirement was to show a the users who have the role "Parent" in a different index view. In addition to that, I wanted to show all other users except "Parents" in another view. In both cases, I wanted to hide the administrator account, which is why "whereNotIn()" method was used.

So now I actually filter the users based on their roles in the view itself. For that I used the following two code segments inside the foreach loop in "parents.index" view and "users.index" view respectively.

@foreach($users as $user)
@if($user->hasRole('Parent'))
<tr>
    <td>
    <td>
    ...
</tr>
@endif
@endforeach
@foreach($users as $user)
@if(!$user->hasRole('Parent'))
<tr>
    <td>
    <td>
    ...
</tr>
@endif
@endforeach

Thanks again! :)

Please or to participate in this conversation.