Laravel : Order by string date using query builder with MySql - php

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();

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();

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();

Related

How to combine two counts using Laravel

Using Laravel 8 for a restful API.
A table in the database has following fields
report_date , supervisor_id and supervisor_note
I want to retrieve a result that counts the number of reports on any given day date and also counts all of the null values in supervisor_notes field.
I am using the following Laravel code:
$reports=DB::table('reports')
->where('supervisor_id','like', '%'.$supervisor_id.'%')
->select('report_date', DB::raw('count(*) as total'))
->groupBy('report_date')
->get();
I don't know how to combine the code with the second count condition in the same query
You can use conditional aggregation here
$reports=DB::table('reports')
->where('supervisor_id','=', $supervisor_id)
->select([
'report_date',
DB::raw('count(*) as total'),
DB::raw('sum(case when supervisor_note is null or supervisor_note = "" then 1 else 0 end) as notes_total')
])
->groupBy('report_date')
->get();
Also if supervisor_id is integer column and $supervisor_id also holds integer value then use exact integer matching like = instead of using string comparison using like clause

Ordering records using dates in Laravel eloquent

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.
try STR_TO_DATE
$data = User::orderBy(DB::raw("STR_TO_DATE(CONCAT('01-', move_out),'%d-%m/%Y')"), 'DESC')->get();
Try to use DATE_FORMAT:
$items = DB::table("users")
->orderBy(DB::raw("DATE_FORMAT(move_out,'%M/%Y')"), 'DESC')
->get();

Get min(date), max(date) with group by eloquent laravel

This query is for getting other data with the highest value of date with the group by/unique. Here I used unique in place of group by.
My question is how to get min(date) and max(date) with group by/unique.
The group by/unique is for Dataset table's date field.
I have searched for this but not getting exact solution that how to get max and min date with group by/unique in laravel eloquent.
In table structure, there are multiple entries for one code so here I used group by/unique to get one record for the code.
There can be multiple dates as 02-01-2003,01-03-2007,01-01-2019, 01-07-2018... etc. with same/ different code. If I group by with code then get onmy one record per code. So here I want to select the max date [01-01-2019] and min date [02-01-2003].
Thanks in advance.
Controller:
$datasets = Dataset::where('user_id', $user_id)
->orderBy('date','desc')
->get(['code', 'access','user_id','date'])
->unique('code');
Finally I got solution but this can not be the exact solution but as I am beginner and not getting the exact solution I do this functionality as below:
I created two different queries to get min and max values.
$min_datasets = Dataset::where('user_id', $user_id)
->orderBy('date','asc')
->get(['code', 'access','user_id','date'])
->unique('code');
$max_$datasets = Dataset::where('user_id', $user_id)
->orderBy('date','desc')
->get(['code', 'access','user_id','date'])
->unique('code');
Try to select max and min date like this:
$datasets = Dataset::select('code', 'access','user_id', DB::raw('MAX(date) as max_date'), DB::raw('MIN(date) as min_date'))
->where('user_id', $user_id)
->orderBy('date','desc')
->get()
->unique('code');
$data = DB::table('table_name')->where('user_id',$user_id)
->select('code','access','user_id','date')
->whereBetween('date', [02-01-2003, 01-01-2019])
->groupBy('unique_column')
->get()

how to orderby() count without group in laravel

I have Users table which has under_reference column that represents by whom this user was referred.
I want to order user by having highest under_reference count. How to order by counting under reference
$data['user'] = User::orderBy('id','DESC')->get();
$data['user'] = User::select(DB::raw('count(*) as total'))
->groupBy('under_reference')
->orderBy('under_reference','DESC')
->get();
Here is the query that can help you. You can get the total users referred by a person and orderBy reference.
Use Group By for this situation, and sort from it. Here's an example.
$query = [
'name',
'email',
// store count of under_reference as total
DB::raw('count(under_reference) as total')
];
$sorted = User::groupBy('name', 'email')
->select($query)
->orderBy('total', 'desc') // remember total before, sort it by desc or asc
->get();
You can refer from laravel documentation here on raw expressions
The name and email is just an examaple, as you didn't show us what your table's column looks like. But you should get a pretty rough idea
i created another column totalref with Integer . i coded logic to update this column also with referral bonus and then orderby totalref. and it worked like magic
Try this:
$user_info = DB::table('users')
->select('under_reference',DB::raw('count(under_reference) as ur'))
->groupBy('under_reference')
->orderBy('ur','DESC')
->get();
You can try in this way also worked.
$data['user'] = DB::select('SELECT *` FROM `user` ORDER BY
CAST(`under_reference` AS decimal) DESC');
You can cast the DB column varchar to decimal in query.

Laravel, filter timestamp by date only

I want to filter a table by user ID and the created_at field. The only thing is created_at is a timestamp, and I want to query by date only not time.
So something like -
$messages = Message::where(['from' => $fromUser->id, 'created_at' => 'TODAY'S DATE'])->get();
$query->whereDate('created_at', '=', date('Y-m-d'));
or
$query->whereDate('created_at', '=', Carbon::today()->toDateString());
The only way I know (in Laravel) to compare a DATE against created_at is to use whereRaw, so for your example, you'd use something like:
Message::where(...)->whereRaw('DATE(created_at) = ?', [$today])->get();
You can find more information about Eloquent and it's other methods here

Categories