I want to sort the results by the date, but this Laravel 5 SQL Query is not working as i want.
$b = DB::table('entry')
->select(DB::raw("DATE_FORMAT(created_at,'%d-%m-%Y') as tanggal"))
->groupBy(DB::raw("DATE_FORMAT(created_at,'%d-%m-%Y')"))
->orderBy(DB::raw("DATE_FORMAT(created_at,'%d-%m-%Y')"), 'asc')
->get();
ORDER BY is a clause in SQL which is used with SELECT query to fetch the records in ascending or descending order from a table. Just like we sort the integer and the string values stored in the column of the tables, similarly, we can sort the dates stored in the SQL table's column.
Use the ORDER BY keyword and the name of the column by which you want to sort. This way, you'll sort the data in ascending order by this column. You could also use the ASC keyword to make it clear that the order is ascending (the earliest date is shown first, the latest date is shown last, etc.).
The first method to get the query of an Eloquent call is by using the toSql() method. This method returns the query without running it – good if you don't want to alter data and only get the query – but this method doesn't show the whole query if your query is more complex or if there are sub-queries.
If you'd like to see the latest date first and the earliest date last, you need to sort in descending order. Use the DESC keyword in this case. ORDER BY exam_date DESC ; Note that in MySQL, NULL s are displayed first when sorting in ascending order and last when sorting in descending order.
Here's the easy way to achieve this
Step 1 :
Create a Model named as Entry
by artisan command or manually
Step 2 :
Then from your Controller just do
$entry = Entry::orderBy('created_at', 'ASC')->get();
Then you should get the $entry
array of what you need.
Hope this helps you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With