how to compare two date in laravel - php

I'm having a hard time in comparing two date in laravel, I try this code
below in mysql and it works well but when I transfer it on laravel it doesn't work
SELECT * FROM `holiday` WHERE date_format(holiday.date,'%m-%d') = date_format('2017-05-15','%m-%d')
here is my code in laravel
public function getHoliday(){
$date = '2017-05-15';
$data = DB::table('holiday')
->select(
'holiday.id'
)
->whereRaw("date_format(holiday.date, '%m-%d') "=" date_format($date, '%m-%d')")
->first();
return $data;
}
I do hope you could help me with my code, I just want to compare day and month of two date

$data = DB::table('holiday')
->select([
'holiday.id',
'holiday.date',
])
->whereRaw("date_format(holiday.date, '%m-%d') = date_format('$date', '%m-%d')")
->first();

Try changing this line :
->whereRaw("date_format(holiday.date, '%m-%d') "=" date_format($date, '%m-%d')")
to this
->where(date_format(holiday.date, '%m-%d') , date_format($date, '%m-%d'))
EDIT.
try to use this date helpers instead
->whereDay('date', '=', date('d'))
->whereMonth('date', '=', date('m'))
->first();

Related

How to use WhereBetween date with %LIKE% in sql query

In my database creadted_at data 2017-11-07 18:58:16,2017-11-07 19:58:16. I try to use WhereBetween for searching data in date 2017-11-07
Am not sure How can I put Like % % into my query
'like', '%'.2017-11-07.'%'
->WhereBetween('created_at', ['2017-11-07', '2017-12-07'])
Here is my full controller
$b = DB::table("v_dealer_sell_time")
->select([
'product_name',
DB::raw('COALESCE(SUM(total_price), 0) AS total_price'),
DB::raw('COALESCE(SUM(total_product), 0) AS total_product')
])
->WhereBetween('created_at', ['2017-11-07', '2017-11-07'])
->groupBy('product_name')
->get();
If you want the created ones in the same given date you can use whereDate like this But since 5.3 (Documentation):
$b = DB::table("v_dealer_sell_time")
->select([
'product_name',
DB::raw('COALESCE(SUM(total_price), 0) AS total_price'),
DB::raw('COALESCE(SUM(total_product), 0) AS total_product')
])
->WhereDate('created_at', '=', $date)
->groupBy('product_name')
->get();
If you want it from between two dates use whereBetween like this :
$b = DB::table("v_dealer_sell_time")
->select([
'product_name',
DB::raw('COALESCE(SUM(total_price), 0) AS total_price'),
DB::raw('COALESCE(SUM(total_product), 0) AS total_product')
])
->WhereBetween('created_at', [Carbon::parse('2017-11-07')->startOfDay(), Carbon::parse('2017-12-07')->endOfDay()])
->groupBy('product_name')
->get();
PS : Do not forget to add use Carbon\Carbon; at the top of your Controller.
Use whereDate():
$date = Carbon::parse($date)->toDateString();
....
->whereDate('created_at', $date)
Or whereBetween():
$date = Carbon::parse($date);
$from = $date->copy()->startOfDay();
$to = $date->copy()->endOfDay();
....
->whereBetween('created_at', [$from, $to])
If this Date search related to a Search Function, then you have to do something like this
Code
Change this to
->WhereBetween('created_at', ['2017-11-07', '2017-11-07'])
this
->WhereBetween('created_at', ['2017-11-07 00:00:00', '2017-11-07 23:59:59'])
WHY ??
2017-11-07 00:00:00 - Start of the day
2017-11-07 23:59:59 - end of the day
if you use tosql() and check your query it has something like this
.`created_at` between ? and ? "

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 4.2: How to convert raw query to Eloquent

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;
}

Laravel $q->where() between dates

I am trying to get my cron to only get Projects that are due to recur/renew in the next 7 days to send out reminder emails. I've just found out my logic doesn't quite work.
I currently have the query:
$projects = Project::where(function($q){
$q->where('recur_at', '>', date("Y-m-d H:i:s", time() - 604800));
$q->where('status', '<', 5);
$q->where('recur_cancelled', '=', 0);
});
However, I realized what I need to do is something like:
Psudo SQL:
SELECT * FROM projects WHERE recur_at > recur_at - '7 days' AND /* Other status + recurr_cancelled stuff) */
How would I do this in Laravel 4, and using the DATETIME datatype, I've only done this sort of thing using timestamps.
Update:
Managed to solve this after using the following code, Stackoverflow also helps when you can pull bits of code and look at them out of context.
$projects = Project::where(function($q){
$q->where(DB::raw('recur_at BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()'));
$q->where('status', '<', 5);
$q->where('recur_cancelled', '=', 0);
});
Updated Question: Is there better way to do this in Laravel/Eloquent?
Update 2:
The first resolution ended up not been right after further testing, I have now resolved and tested the following solution:
$projects = Project::where(function($q){
$q->where('recur_at', '<=', Carbon::now()->addWeek());
$q->where('recur_at', '!=', "0000-00-00 00:00:00");
$q->where('status', '<', 5);
$q->where('recur_cancelled', '=', 0);
});
You can chain your wheres directly, without function(q). There's also a nice date handling package in laravel, called Carbon. So you could do something like:
$projects = Project::where('recur_at', '>', Carbon::now())
->where('recur_at', '<', Carbon::now()->addWeek())
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
Just make sure you require Carbon in composer and you're using Carbon namespace (use Carbon\Carbon;) and it should work.
EDIT:
As Joel said, you could do:
$projects = Project::whereBetween('recur_at', array(Carbon::now(), Carbon::now()->addWeek()))
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
Didn't wan to mess with carbon. So here's my solution
$start = new \DateTime('now');
$start->modify('first day of this month');
$end = new \DateTime('now');
$end->modify('last day of this month');
$new_releases = Game::whereBetween('release', array($start, $end))->get();
#Tom : Instead of using 'now' or 'addWeek' if we provide date in following format, it does not give correct records
$projects = Project::whereBetween('recur_at', array(new DateTime('2015-10-16'), new DateTime('2015-10-23')))
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
it gives records having date form 2015-10-16 to less than 2015-10-23.
If value of recur_at is 2015-10-23 00:00:00 then only it shows that record
else if it is 2015-10-23 12:00:45 then it is not shown.
Edited: Kindly note that whereBetween('date',$start_date,$end_date) is inclusive of the first date.

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