Reputation: 2000
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 :
$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 .
Upvotes: 1
Views: 63
Reputation: 551
Use like this
$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);
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');
}
$data = $data->paginate(10);
Upvotes: 1