psudo
psudo

Reputation: 1558

Unable to sort records according to price laravel

I'm trying to sort the db records(tours) according to price (lowest to highest, highest to lowest). And I've added 12 dummy records in db with prices (100 to 1200) in series respectively. Below is my code in controller for performing the sort query:

    public function short(Request $request)
{
    if ($request->sortby == "lower") {
        $query = Tour::query()->orderBy('price', 'asc');
        if (!empty($request->country)) {
            $query = $query->whereHas('country', function($r) use($request) {
                $r->where('countries.name', $request->country);
            });
        }            

        if (!empty($request->category)) {
            $query = $query->whereHas('category', function($s) use($request) {
                $s->where('categories.name', $request->category);
            });
        }

        if ($request->days !== null) {
            $days = $request->days;
            $days_explode = explode('|', $days);
            $query = $query->whereBetween('days', [$days_explode[0], $days_explode[1]]);                    
        }
        $query = $query->get();   
    }
    else{
        $query = Tour::query()->orderBy('price', 'desc');            
        if (!empty($request->country)) {
            $query = $query->whereHas('country', function($r) use($request) {
                $r->where('countries.name', $request->country);
            });
        }            

        if (!empty($request->category)) {
            $query = $query->whereHas('category', function($s) use($request) {
                $s->where('categories.name', $request->category);
            });
        }

        if ($request->days !== null) {
            $days = $request->days;
            $days_explode = explode('|', $days);
            $query = $query->whereBetween('days', [$days_explode[0], $days_explode[1]]);                    
        }
        $query = $query->get();               
    }

    return view('public.tour.search')->withResults($query);
}  

When sort by lowest to highest is selected, records are displayed in the following order according to price price column of db table:

100,1000,1100,1200,200,300,400,500,600,700,800,900

and when highest to lowest is selected records are displayed in the following order according to price price column of db table:

900,800,700,600,500,400,300,200,1200,1100,1000,100

Can anyone help me please ?

Upvotes: 0

Views: 2082

Answers (2)

V16
V16

Reputation: 119

Put the Order By Query at end.

$query = $query->orderBy('price', 'asc')->get();

Upvotes: 1

Niraj Shah
Niraj Shah

Reputation: 15457

What is the data type for the price column in the database?

It should be a numerical format like double or integer for the sorting to work correctly.

Upvotes: 1

Related Questions