Laravel 4.2: How to convert raw query to Eloquent - php

I have a raw query which works fine.
$qry ="select date(created_at) as Date,count(id) as Value from performances where date_format(created_at,'%d-%m-%Y') >= '$start_date' and date_format(created_at,'%d-%m-%Y') <= '$to_date' group by Date order by Date desc ";
$stats = DB::select( DB::raw($qry) );
return json_encode($stats);
I would like to convert it in to Eloquent
My controller function is
public function postPerformanceDetails()
{
$start_date = Input::get('start_date');
$to_date = Input::get('to_date');
$start_date = date('Y-m-d',strtotime($start_date));
$to_date = date('Y-m-d',strtotime($to_date));
$stats = Performance::where('created_at', '>=', $start_date)
->where('created_at','<=',$to_date)
->groupBy('perf_date')
->orderBy('perf_date', 'DESC')
->remember(60)
->get([
DB::raw('Date(created_at) as perf_date'),
DB::raw('COUNT(id) as perf_count')
])
->toJSON();
return $stats
}
The raw query works fine but eloquent does not work according to the date input.
I input data in this format 09-03-2015
in database the format is 2015-03-09
If we give 2015-03-09 as start_date and to_date it returns empty string.
Is there any problem with formats?
How can i solve this issue?

The easiest way would be to convert the date in PHP to the database format.
$start_date = date('Y-m-d', strtotime($start_date));
This should lead to your database format: 2015-03-09.

I got the answer as #sleepless suggested.
This is the code.
public function postPerformanceDetails()
{
$event = Input::get('events');
$start_date = Input::get('start_date');
$to_date = Input::get('to_date');
$start_date = date('Y-m-d H:i:s',strtotime($start_date.'00:00:00'));
$to_date = date('Y-m-d H:i:s',strtotime($to_date.'23:59:59'));
$stats = Performance::where('created_at', '>=', $start_date)
->where('created_at','<=',$to_date)
->groupBy('perf_date')
->orderBy('perf_date', 'DESC')
->remember(60)
->get([
DB::raw('Date(created_at) as perf_date'),
DB::raw('COUNT(id) as perf_count')
])
->toJSON();
return $stats;
}

Related

Why does the query by date range not work when different years are involved?

I have a query for date range in Laravel that brings me to my head. Initially the query works without errors but I have detected that if the date range is between different years (12-2020 to 01-2021) it does not return any records. I'm a little tired of checking the code and I don't see the problem.
I put here the query that saves the data in an array and the check that I do later to apply the filter of the dates before returning the values.
public function getData($filters) {
$tasks = $this->getModel()
->whereIn('tasks.department_id', $filters['departmentIds'])
->join('departments', 'departments.id', '=', 'tasks.department_id')
->join('deliverables as dev', 'dev.id', '=', 'tasks.deliverable_id')
->leftJoin('deliverables as sub', 'sub.id', '=', 'tasks.subdeliverable_id')
->leftJoin('workers as st_workers', 'st_workers.id', '=', 'tasks.start_worker_id')
->leftJoin('workers as end_workers', 'end_workers.id', '=', 'tasks.end_worker_id')
->leftJoin('type_task_statuses', 'type_task_statuses.id', '=', 'tasks.status_id')
->leftJoin('incidences', 'incidences.task_id', '=', 'tasks.id')
->select('tasks.id', 'departments.name as department', 'tasks.start_worker_id', 'tasks.end_worker_id', 'st_workers.short_name as start_worker',
'end_workers.short_name as end_worker', 'tasks.plane', 'tasks.st', 'dev.name as deliverable', 'sub.name as subdeliverable',
'tasks.quantity', 'tasks.other_deliverable', 'tasks.start_prevision_date', 'tasks.end_prevision_date', 'tasks.start_date',
'tasks.end_date', 'tasks.prevision_hour', 'tasks.incurred_hour', 'type_task_statuses.display_name as status', 'type_task_statuses.color', 'tasks.advance', 'tasks.agreed',
'tasks.disagreed_date', 'tasks.supervised', DB::raw('COUNT(incidences.id) as count_incidences'))
->groupBy('tasks.id');
if (array_key_exists('fromDate', $filters) && $filters['fromDate']) {
$tasks->whereRaw('(DATE_FORMAT(tasks.end_date, "%m-%Y") >= "'.$filters['fromDate'].'" OR tasks.end_date is NULL)');
}
if (array_key_exists('toDate', $filters) && $filters['toDate']) {
$tasks->whereRaw('(DATE_FORMAT(tasks.end_date, "%m-%Y") <= "'.$filters['toDate'].'" OR tasks.end_date is NULL)');
}
return $tasks;
}
I would suggest to format your input to date range in your application rather than applying formatting on database side see my another answer for anit-patterns
Let say you have following input to match the date in database
$filters['fromDate'] ='12-2020';
$filters['toDate'] = '01-2021';
Which is equivalent to following date range in actual
From 2020-12-01 00:00:00 To 2021-01-31 23:59:59
So lets try to convert the filters input to this range format
/** 2020-12-01 00:00:00 */
$fromDate = \Carbon\Carbon::createFromFormat('d-m-Y', '01-'.$filters['fromDate'])->startOfMonth()->format('Y-m-d H:i:s');
/** 2021-01-31 23:59:59 */
$toDate = \Carbon\Carbon::createFromFormat('d-m-Y', '01-'.$filters['toDate'])->endOfMonth()->format('Y-m-d H:i:s');
Now you can easily apply these ranges in your query and on database side you wont need any kind of formatting
if (array_key_exists('fromDate', $filters) && $filters['fromDate']) {
$fromDate = \Carbon\Carbon::createFromFormat('d-m-Y', '01-' . $filters['fromDate'])->startOfMonth()->format('Y-m-d H:i:s');
$tasks->where(function ($query) use ($fromDate) {
$query->whereNull('tasks.end_date')
->orWhere('tasks.end_date', '>=', $fromDate);
});
}
if (array_key_exists('toDate', $filters) && $filters['toDate']) {
$toDate = \Carbon\Carbon::createFromFormat('d-m-Y', '01-' . $filters['toDate'])->endOfMonth()->format('Y-m-d H:i:s');
$tasks->where(function ($query) use ($toDate) {
$query->whereNull('tasks.end_date')
->orWhere('tasks.end_date', '<=', $toDate);
});
}

DateTime::__construct() expects parameter 1 to be string, object given

I am trying to get two date calculation . when i placed
$from = Carbon::createFromFormat('m-d-Y H:i:s', '02-10-2017 10:02:20');
code i get value but when i placed data from mysql
$from = Carbon::createFromFormat('m-d-Y H:i:s', $from_date);
can not find data, and can not calculation to and from date
Controller.php
public function circulerMatchView()
{
$user_id = Auth::user()->id;
$resume_exp = Experience::select('user_exp_keyword')
->where('user_id','=',$user_id)
->get();
$from_date = Experience::selectRaw('exp_from_date')
->where('user_id','=',$user_id)
->orderBy('exp_from_date','desc')
->take(1)
->get();
$to_date = Experience::selectRaw('exp_to_date')
->where('user_id','=',$user_id)
->orderBy('exp_from_date','desc')
->take(1)
->get();
$from = DateTime::createFromFormat('m-d-Y H:i:s', $from_date);
$to = Carbon::createFromFormat('m-d-Y H:i:s', $to_date);
$realAge = Carbon::parse($to)->diff(Carbon::parse($from))->format('%y');
print_r($realAge);
}
if $from_date is 02-21-2017 and $to_date is 02-21-2018
result is 1 year
You are fetching array by using get. Replace these two lines with your codes and check. It will fetch only field data values.
$from_date = Experience::
where('user_id','=',$user_id)
->orderBy('exp_from_date','desc')
->take(1)
->pluck('exp_from_date')[0];
$to_date = Experience::
where('user_id','=',$user_id)
->orderBy('exp_to_date','desc')
->take(1)
->pluck('exp_to_date')[0];
Once check this documentation for details about pluck.

Laravel - where less/greater than date syntax

This is not showing the correct count. What is the correct syntax ?
$this->data['Tasks'] = \DB::table('tb_tasks')->where('Status', 'like', 'Open%')->whereDate('DeadLine', '>', 'CURDATE()')->count();
Use a Carbon instance:
$this->data['Tasks'] = \DB::table('tb_tasks')->where('Status', 'like', 'Open%')->whereDate('DeadLine', '>', Carbon::now())->count();
You can also use the now() helper
$this->data['Tasks'] = \DB::table('tb_tasks')->where('Status', 'like', 'Open%')->whereDate('DeadLine', '>', now())->count();
Use DB::raw:
->where('datefield', '>', \DB::raw('NOW()'))
We can also try this one. It works for me.
$date = "2020-04-10";
/*
Assumimng DB `login_date` datetime format is "Y-m-d H:i:s"
*/
$from_date = $date.' 00:00:01';
->where('login_date', '>=', $from_date);
By adding Where Clause in the query, we can find the result having
rows after the particular date.
Option-2:
$date = "2020-03-25"; // Format: date('Y-m-d);
$orders = DB::table('orders')
->select('*')
->whereDate('order_datetime', '<=', $date)
->get();
// Here, Table Field "order_datetime", type is "datetime"
// Assuming DB `order_datetime` stores value format like: "Y-m-d H:i:s"
you can make use of whereDate like below:
$query->whereDate('DeadLine', '>', Carbon::now())->count();

Laravel eloquent get model on date

I want to get all users created on a specified date:
// $date is a Carbon instance parsed from command line argument.
// I checked it and it is correct.
$users = User::where('created_at', '>', $date->startOfDay())
->where('created_at', '<', $date->endOfDay())
->get();
But this returns 0 results, whereas in the database there are rows that correspond to that date.
What am I doing wrong?
Carbon doesn't behave like value object (ie. it's not immutable), so this:
$date->startOfDay();
$date->endOfDay();
simply modifies the $date object and returns it back. That being said, the string that is passed to the query, is obtained when PDO binds it in the prepared statement, when $date is already mutated to endOfDay.
It means that you just pass reference to the object:
$start === $end; // true
So either use different objects:
$users = User::where('created_at', '>', $date->copy()->startOfDay())
->where('created_at', '<', $date->copy()->endOfDay())
->get();
or simply return the string you need in place, instead of the Carbon object:
$users = User::where('created_at', '>', $date->startOfDay()->toDateTimeString())
->where('created_at', '<', $date->endOfDay()->toDateTimeString())
->get();
still, $date will now hold xxxx-xx-xx 23:59:59 timestamp, so keep this in mind in case you need to work with this variable somewhere else.
The problem is not Laravel itself here but Carbon.
When using the following code:
use Carbon\Carbon;
$date = new Carbon('2014-10-07');
$start = $date->startOfDay();
$end = $date->endOfDay();
echo $start.' '.$end;
what you get is:
2014-10-07 23:59:59 2014-10-07 23:59:59
so Laravel will execute query:
select * from `users` where `created_at` >'2014-10-07 23:59:59' and `created_at` <'2014-10-07 23:59:59';
and obviously you will get no results.
As you see $start result is not what you expect here.
to make it work the solution I found is creating 2 carbon objects:
use Carbon\Carbon;
$date = new Carbon('2014-10-07');
$date2 = new Carbon('2014-10-07');
$start = $date->startOfDay();
$end = $date2->endOfDay();
echo $start.' '.$end;
Now result is as expected:
2014-10-07 00:00:00 2014-10-07 23:59:59
Now you can use:
use Carbon\Carbon;
$date = new Carbon('2014-10-07');
$date2 = new Carbon('2014-10-07');
$users = User::where('created_at', '>', $date->startOfDay())
->where('created_at', '<', $date2->endOfDay())
->get();
or
use Carbon\Carbon;
$date = new Carbon('2014-10-07');
$date2 = new Carbon('2014-10-07');
$users = User::whereBetween('created_at', [$date->startOfDay(), $date2->endOfDay()])->get();
In your query lefts the table name:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
Look: http://laravel.com/docs/4.2/queries#selects

Laravel 4 Eloquent Query

I am trying to query the 'created_at' field by the date for today:
$today = DATE('Y-m-d');
$logs = DB::table('bglogs')->where('DATE('created_at')','=',$today)->where('user_id','=',Auth::user()->id)->get();
It tells me that DATE('created_at') is an unknown column? Any suggestions, relatively new to Eloquent so I am sure I've missed something obvious.
Thanks in advance!
EDIT: 6/10/2014
Wanted to note that I had to tweak it a bit as it was bringing back all records rather than a specific date. Not sure why. I finally got this working correctly. Thanks again to all who answered and I hope this update will help others in the future:
$logs = DB::select(DB::raw("SELECT * FROM bglogs WHERE DATE(created_at) = :today AND user_id = :user"), array('today'=>DATE('Y-m-d'), 'user'=>Auth::user()->id));
If you want to use mysql functions you must use whereRaw and wite it in a single string.
In the other where, you can skip the second parameter if it will be equals (=).
$today = DATE('Y-m-d');
$logs = DB::table('bglogs')
->select(DB::raw('*'))
->whereRaw("DATE('created_at') = " . $today)
->where('user_id', Auth::user()->id)
->get();
Hope its help you.
I recommend you dont declare alias if you will use the var just one time:
$logs = DB::table('bglogs')
->select(DB::raw('*'))
->whereRaw("DATE('created_at') = " . DATE('Y-m-d'))
->where('user_id', Auth::user()->id)
->get();
You may try this (Carbon is available with Laravel):
$today = Carbon\Carbon::toDay()->toDateTimeString();
$logs = DB::table('bglogs')->where('created_at', $today)
->where('user_id', Auth::user()->id)
->get();
there is no need to use raw method when you can just define search criteria.
try this:
$today = DATE('Y-m-d');
$logs = DB::table('bglogs')
->where('created_at', '=>', $today.' 00:00:00')
->where('created_at', '<=', $today.' 23:59:59')
->where('user_id', '=', Auth::user()->id)
->get();
if problem still exists so check your table for existence of this created_at field.
$today=date("Y-m-d");
$coustomers=Coustomer::where('created_at','like',"$today%")->get();
You can use Carbon class provided by laravel:
$today = Carbon::today();
$logs = DB::table('bglogs')
->where('created_at','>=',$today)
->where('user_id','=',Auth::user()->id)
->get();
Or
You can use php date functions to do this manually:
$today = new \DateTime(date('F jS Y h:i:s A', strtotime('today')));
$logs = DB::table('bglogs')
->where('created_at','>=',$today)
->where('user_id','=',Auth::user()->id)
->get();

Categories