0

I have a column move_out that stores date in this format - m/Y e.g 02/2020. I want to order the records in that table by the move_out column in descending order but my solution don't seem to be working. It does not arrange the records appropriately. This is what I am doing.

$data = User::orderBy('move_out', 'DESC')->get();

How do I solve this?

The datatype for the move_out column is string.

4
  • 1
    The simple answer is store dates in the database ALWAYS as DATE or DATETIME. If you want to show dates in any other way that is a job for the presentation layer# Commented Mar 7, 2020 at 16:04
  • If you want a reliable sort you are going to have to use some SQL functions in your query to convert that string into a valid MySQL date. Commented Mar 7, 2020 at 16:08
  • move_out column type is varchar ? Commented Mar 7, 2020 at 16:10
  • Yes @RonakDhoot Commented Mar 7, 2020 at 16:12

2 Answers 2

3

try STR_TO_DATE

$data = User::orderBy(DB::raw("STR_TO_DATE(CONCAT('01-', move_out),'%d-%m/%Y')"), 'DESC')->get();
Sign up to request clarification or add additional context in comments.

5 Comments

It does not. Not even ordering
I hope you are aware, the date is stored in this format - 02/2020. Hope it does not affect your answer?
@radioactive see screenshot
Please don't post screenshots of text
@Strawberry: removed
2

Try to use DATE_FORMAT:

$items = DB::table("users")
           ->orderBy(DB::raw("DATE_FORMAT(move_out,'%M/%Y')"), 'DESC')
           ->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.