I have a very simple solution but I dislike that. So, How can I do?
My database:
--------------------------------------
id name view created_at
--------------------------------------
1 one 9 2021-01-13 12:34:22
2 two 8 2021-01-15 10:23:02
3 three 23 2021-01-15 20:55:17
4 forth 15 2021-01-16 12:34:22
5 fifth 0 2021-01-19 10:37:02
I want to sort and get my data like this:
--------------------------------------
id name view created_at
--------------------------------------
5 fifth 0 2021-01-19 10:37:02
3 three 23 2021-01-15 20:55:17
4 forth 15 2021-01-16 12:34:22
1 one 9 2021-01-13 12:34:22
2 two 8 2021-01-15 10:23:02
My current code is:
$today = '2021-01-19'; //this date will calculate in daily. Not absolute date!
$firstarray = Product::where('created_at', 'LIKE', $today . '%')->get();
$secondarray=Product::orderBy('viewer', 'DESC')->get();
$data = array_merge($firstarray, $secondarray);
return $data;
If today's date was hardcoded, it would be:
$today = '2021-01-19'; //this date will calculate in daily. Not absolute date!
$data = Product::orderBy(DB::raw('FIELD(created_at, LIKE $today . "%")'),'DESC')
->orderBy('view', 'desc')->get();
return $data;
I need a dynamic query to sort by today's date, then by view
valued DESC.
I am using Laravel 6.
Your question is not clear! If it's the way I understand, that's the solution.
$data = Product::whereDate('created_at', now())->orderBy('view','desc')->get();