How to order by custom time format in laravel?

by aniya.jaskolski , in category: PHP General , 2 months ago

How to order by custom time format in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 2 months ago

@aniya.jaskolski 

To order by a custom time format in Laravel, you can use the orderByRaw method along with the CAST function to convert the time format and then order accordingly.


Here is an example:

1
2
3
4
$users = DB::table('users')
            ->select('*')
            ->orderByRaw("CAST(created_at AS TIME) ASC")
            ->get();


In this example, we are ordering the records from the users table by the created_at column, which is assumed to be a timestamp. We are converting the created_at column to a time format using the CAST function with the AS TIME parameter. Finally, we are ordering the records in ascending order using the ASC parameter.


You can modify this example as per your requirement by replacing the table name, column name, and the desired time format.