Reputation: 99
I can't seem to get how to order by month in Laravel 7. I use different columns for my month, day, year and time and instead of ordering it by month, it orders the months alphabetically.
Intended Result: January, February, March, April
Actual Result: April, February, January, March
This is my code:
$ledgers = Ledger::orderBy('month', 'DESC')
->orderBy('day', 'DESC')
->orderBy('year', 'DESC')
->orderBy('time', 'DESC')
->where('user_id', auth()->user()->id)
->paginate(8);
Upvotes: 1
Views: 2030
Reputation: 12188
first of all: i must say that you should store your date info in database in datetime column like Tim Lewis said in comment ...
any way you can use order by fields , this kind of order make the result ordered according to the fields you provide ...
$ledgers = Ledger::orderByRaw('FIELD(month,'January','February','March','May', 'June','July','August','September','October','November','December')')
->orderBy('day', 'DESC')
->orderBy('year', 'DESC')
->orderBy('time', 'DESC')
->where('user_id', auth()->user()->id)
->paginate(8);
please see:
https://stackoverflow.com/a/9378709/10573560
Upvotes: 2