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

muuucho's avatar
Level 11

Can't loop over paginated data

I try to fetch posts from a database and display them in a blade file, but I get the error foreach() argument must be of type array|object, null given Why?

UserList.php, render()

public function render(): View
    {
        $usersQuery = TeamUser::query()
            ->select(['team_user.*'])
            ->where('team_id', Auth::user()->team_id);

        $paginatedUsers = $usersQuery->paginate(10);
              
        // Pass the paginated results to the view
        return view('livewire.users-list', ['teamUsers' => $paginatedUsers]);
    }

users-list.blade.php

@foreach($teamUsers as $teamUser)
   //display each user...
@endforeach
0 likes
2 replies
muuucho's avatar
Level 11

If I dd(paginatedUsers), I get

Illuminate\Pagination\LengthAwarePaginator {#1996 ▼ // app\Livewire\UsersList.php:40
  #items: 
Illuminate\Database\Eloquent
\
Collection {#2000 ▼
    #items: array:2 [▼
      0 => 
App\Models
\
TeamUser {#2001 ▼
        #connection: "mysql"
        #table: "team_user"
        #primaryKey: "id"
        #keyType: "int"
        +incrementing: true
        #with: []
        #withCount: []
        +preventsLazyLoading: false
        #perPage: 15
        +exists: true
        +wasRecentlyCreated: false
        #escapeWhenCastingToString: false
        #attributes: array:15 [▼
          "id" => 1
          "team_id" => 1
          "user_id" => 1
			..... and so on
muuucho's avatar
muuucho
OP
Best Answer
Level 11

This works:

$usersQuery = TeamUser::query()
            ->select(['team_user.*'])
            ->where('team_id', Auth::user()->team_id);

        $paginatedUsers = $usersQuery->paginate(10);
        $teamUsers = collect($paginatedUsers->items());            

        // Pass the paginated results to the view
        return view('livewire.users-list', ['teamUsers' => $teamUsers]);

Please or to participate in this conversation.