laravel eloquent order by varchar as int

611 0 0 0

Last Updated : 2024-02-22 13:21:41

Sometimes, You will need to order by a varchar column as an integer. for example if you have the billNumbers in two rows as 5 and 1400 the order as varchar in desc order will get that with 5 first then that with 1400. While the opposite is what is wanted in the ordering using integers.

//orderByRaw('CONVERT(billNumber, SIGNED) desc')
$lastBillNumber = ProvincialBill::where('assembly', $element['province'])->orderByRaw('CONVERT(billNumber, SIGNED) desc')->first() ;

return $query->orderByRaw('CAST(billNumberAS DECIMAL)' desc);

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .