use a callback I think
$sorted = $reservations->sortBy(function ($reservation) {
return $reservation->booking->plot_id;
});
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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.
use a callback I think
$sorted = $reservations->sortBy(function ($reservation) {
return $reservation->booking->plot_id;
});
Please or to participate in this conversation.