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

farshadf's avatar

how to sort a query base on 2 different conditions in laravel

i have a query in laravel that i want my user to be able to sort it in 2 different ways . one of them is hits which is the model it self field but the other is the field which is in relation of that model that i am loading in my resource :


  $data = Accommodation::with(['city','accommodationFacilities','gallery', 'accommodationRoomsLimited.roomPricingHistorySearch' => function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    }])->when($bed_count, function ($q, $bed_count) {
        $q->with([
            'accommodationRoomsLimited' => function ($q) use ($bed_count) {
                $q->where('bed_count', $bed_count);
            }
        ]);
    })
        ->whereIn('city_id', $city_id)
        ->whereIn('grade_stars', $stars)
        ->orWhere('accommodation_type_id', $type_id)
        ->paginate(10);

so here above the hits filed is existing in accommodation model the price is in roomPricingHistorySearch i want my api to sort by any of the 2 that user sends to it would be conditional i think if user sends sort_price for example it sortt by price and if user sends sort_hit it sorts by hits for api . i tried like below and it worked for the first hits filters :

if(request()->sort_hit ){ // or == 'blabla'
    $data = $data->orderBy('hit');
}elseif(request()->sort_price){ // == A-Z or Z-A for order asc,desc
    $data = $data->orderBy('price');
}

but my problem is that i load the price relationship in my resource like below :

            'rooms' => AccommodationRoomResource::collection($this->whenLoaded('accommodationRoomsLimited')),

now i want to know if there is any way to sort the data in my resource by some fields of that relation that i am loading or if there is any better approach for doing this .

0 likes
0 replies

Please or to participate in this conversation.