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

Filth's avatar
Level 4

SortBy on collection by nested value

I have a reservation model with a relationship to a booking model. My booking Model has a relation to plot (plot_id).

The following code works and gets all the intended results:

$reservations = Reservation::whereHas('booking', function ($query) use ($range) {
            $query->whereBetween('arrived_at', $range);
        })->with('booking')->get();
$ending = Reservation::whereHas('booking', function ($query) use ($range) {
            $query->whereBetween('departured_at', $range);
        })->with('booking')->get();
$reservations = $reservations->merge($ending);

I then want to sort the reservations collection by plot_id which is found within booking.


$reservations->sortBy('plot_id')

The above doesn't work as plot_id is a value in booking.

0 likes
4 replies
Snapey's avatar
Snapey
Best Answer
Level 122

use a callback I think

$sorted = $reservations->sortBy(function ($reservation) {
    return $reservation->booking->plot_id;
});
6 likes
Filth's avatar
Level 4

thanks @snapey, although its only half worked, it would appear that it is only sorting the first half of the bookings and not the $ending even though im calling this after the merge...

Filth's avatar
Level 4

Nevermind, it works fine it was just datatables interfering. Thanks again

kyobul's avatar

You can also sort using dot notation, ex:

$sorted = $reservations->sortBy('booking.plot_id');

6 likes

Please or to participate in this conversation.