How would that work for the user on the page? If I want to see page 3 on a certain users flights, you expect it to remember flight page separately for each user/flight ?
Nov 18, 2022
12
Level 8
Paginating data in nested foreach loop
I have a User model that has a hasMany relationship to Flight model, and I am showing the users with their flights on one page.
I'm having a problem with how can I paginate the users and also paginate the flights that a user has.
If we add pagination for each of the flights of the user isn't there a conflict in the URL because the system doesn't know which user flights to paginate?
I mean after clicking the next page of pagination inside the user's flights it will affect the main pagination of users.
Controller
public function usersWithFlights() {
$users = User::with('flights')->withCount('flights')->paginate(20);
}
Blade view
@forelse ($users as $key => $user)
<h3>{{ $user->name }}</h3>
<hr>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody>
@foreach($user->flights as $flight)
<tr>
<td>{{ $flight->origin }}</td>
<td>{{ $flight->destination }}</td>
</tr>
@endforeach
// How to paginate flights here?
</tbody>
</table>
@empty
No data .
@endforelse
// paginate users here
{{ $users->links() }}
Level 102
@benjamin1509 You could try this
@php
$userFlights = $user->flights->paginate(1, ['*'], 'flights' . $user->id)->withQueryString();
@endphp
1 like
Please or to participate in this conversation.