Why don't you simply try this ?
$users = User::with('invoices')->get();
Then you can display each user once and his invoices list.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a User model which has many Invoices.
class User extends Authenticatable
{
public function invoices()
{
return $this->hasMany(Invoice::class);
}
}
As part of the dashboard, I want to paginate a list of invoices but only show each user once e.g. If a user has multiple invoices, they should only appear on the list once. In addition, I want to sort the overall pagination by the updated_at field on Invoices so that I can have a column on the resulting table showing the last invoice updated at date.
These are my attempts so far:
//Error: column "invoices.id" must appear in the GROUP BY clause or be used in an aggregate function
invoices()->groupBy('user_id')->latest('updated_at')->paginate(25);
//Returns multiple instances of the same user
invoices()->whereRaw('user_id IN (select distinct user_id FROM invoices)')->latest('updated_at')->paginate(25);
//Error: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
invoices()->distinct('user_id')->latest('updated_at')->paginate(25);
Most examples I found are sorted by the ID of invoices, which is not a good solution here as the invoice's highest (max) ID may not necessarily be the last updated invoice for that user.
have you considered hasOneOfMany ?
https://laravel.com/docs/9.x/eloquent-relationships#has-one-of-many
Please or to participate in this conversation.