Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORDER BY "the date" Laravel 5 SQL Query

Tags:

php

laravel-5

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();
like image 748
Muhammad Haryadi Futra Avatar asked Nov 20 '15 06:11

Muhammad Haryadi Futra


People also ask

Can we use order by on date in SQL?

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.

How do I sort by date of birth in SQL?

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.).

How do I get SQL query in Laravel?

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.

What is the order of date in MySQL?

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.


1 Answers

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

like image 169
Sulthan Allaudeen Avatar answered Oct 12 '22 20:10

Sulthan Allaudeen