nrs jayaram
nrs jayaram

Reputation: 3438

Laravel : Order by string date using query builder with MySql

The table have a startDate column which is VARCHAR type, so need to get rows by ascending order using this column.

Tried this :

orderBy(DB::raw("DATE(startDate)"), 'ASC')

the above does not return correct order, how to pass string date in order by clouse?

Example:

'startDate' => '07-Nov-2017'

$items = DB::table("mytable")->orderBy(DB::raw("DATE(startDate)"), 'ASC')->where('userId','=',$userId)->get();

Upvotes: 3

Views: 7786

Answers (2)

Mathieu Ferre
Mathieu Ferre

Reputation: 4412

Gunaseelan was right, but with synthax errors, try this :

$items = DB::table("mytable")->where('userId','=',$userId)->orderByRaw("DATE_FORMAT('d-m-Y',startDate), ASC")->get();

Upvotes: 0

Laerte
Laerte

Reputation: 7083

You need to convert the date to MySQL format. Try to use DATE_FORMAT:

$items = DB::table("mytable")
           ->orderBy(DB::raw("DATE_FORMAT(startDate,'%d-%M-%Y')"), 'ASC')
           ->where('userId','=',$userId)
           ->get();

Upvotes: 8

Related Questions