Nikunj Php Nikunj Php - 27 days ago 9
PHP Question

how to sort query results with nested relation column field in laravel?

$props = Property::with(['rentalUnit','rentalUnit.floor'])->get()->toArray();


I want to sort
rentalunit
collection with field of floor table field
floor_name


Any help would be appreciated

Answer Source

Add this to your Property model

public function rentalUnitOrderByFloorName() 
{
    return $this->rentalUnit()->select('rental_units.*', 'floors.name')->leftJoin('floors', 'floors.rental_unit_id', '=', 'rental_units.id')->orderBy('floors.name');
}

Then

$props = Property::with(['rentalUnitOrderByFloorName','rentalUnitOrderByFloorName.floor'])->get()->toArray();