I would try this.
$users = User::
with('section')
->with(['passport' => function ($query) {
$query->orderBy('passportDate')->last();
}])
->get();
Tell me if it helps ;).
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello. I have three tables
I want to get the user and his latest passport. The user is in one section and can have several (history) passports. Active passport with maximum passportDate
USERS
Table
...
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->foreignId('section_id')->nullable()->constrained();
...
Section
Table
...
$table->string('title');
$table->string('description');
...
Passport
...
$table->date('passportDate')->nullable();
$table->string('firstName')->nullable();
$table->string('middleName')->nullable();
$table->string('lastName')->nullable();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
...
I want to get a set of fields for each user:
"email" "section_title" "firstName" "middleName" "lastName"
My request:
$users = User::select('users.*', 'sections.title', 'passports.firstName', 'passports.middleName', 'passports.lastName')
->leftJoin('sections', 'sections.id', 'users.section_id')
->leftJoin('passports', 'user_id', 'users.id')
->orderBy('firstName')
->get();
The problem is, if a user has multiple passports, the user's entry is duplicated. I need to get for each user data about his last (max passportDate) passport
Solved
$users = User::select('users.*', 'sections.title', 'passports.firstName', 'passports.middleName', 'passports.lastName')
->leftJoin('sections', 'sections.id', 'users.section_id')
->leftJoin('passports', function($query) {
$query->on('passports.user_id','=','users.id')
->whereRaw('passports.passportDate IN (select MAX(a2.passportDate) from passports as a2 join users as u2 on u2.id = a2.user_id group by u2.id)');
})
->get();
Please or to participate in this conversation.