Laravel $q->where() between dates - php

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.

Related

Eloquent: get only the date from timestamp

I want to get all the entries of a specific day for a user.. I don't know how to format the query.
public function getEntry()
{
$entries = Journal::where('id', '=', Auth::id())
->where('created_at', '=', '\Carbon\Carbon::now()->format("l j F Y")')
->get()->first();
return view('home')->with(compact('entries'));
}
I do not know how to format that 'created_at' to match the server time. Any help will be largely appreciated. Thank You.
Use whereDate() to get all entries for the specific day:
->whereDate('created_at', Carbon::today());
Or use whereBetween():
->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->endOfDay()])
Or simple where():
->where('created_at', '>', Carbon::now()->startOfDay())
->where('created_at', '<', Carbon::now()->endOfDay())

Check two timestamps with current date in PHP (Laravel)

I have two timestamps starting_date and ending_date and I need to compare with current time.
I want to do something like this:
$discount_db = Discount::whereActive(1)
->where('starting_date', '<=', $curdate)
->where('ending_date', '>=', $curdate)
->first();
And I want to check this variable. I have an if where I have to check the timestamps, commands and other..
Use Carbon
$curdate = Carbon::now();
$discount_db = Discount::whereActive(1)
->where('starting_date', '<=', $curdate)
->where('ending_date', '>=', $curdate)
->first();
if(count($discount_db)){
//something happen here
}else{
}

Laravel - Advanced Carbon Date Query

I'm trying to write a certain query but I'm failing with it and I'm looking for some help
Here's what I want to do
SELECT all items WHERE created_at is from before this month (July, June,...), and also select the first 3 which are created during this month
this is what I currently have. I've tried numerous times, but I can't figure out the right "WHERE" case
$offertes = DB::table('offertes')
->select('*')
->where('receiver_id', $user_id)
...
->orderby('seen')
->orderby('created_at','desc')
->get();
Something like this should work:
$time = new Carbon\Carbon('first day of this month'); // Get first day of the month.
$time->setTime(0, 0, 0); // Set time to 00:00:00.
....
->where('created_at', '<', $time)
->where(function($q) {
$q->where('created_at', '>', $time)
->orderby('created_at','asc')
->take(3)
})
->get;

Laravel: How to get count of all records created within in current week as of yesterday

I want to get count of one week old created records as of yesterday in laravel using created_at time stamp, I have:
//week date range upto current day
$name_current_day = date("l");
$name_current_week = date("Y-m-d",strtotime('monday this week')).'to'.date("Y-m-d",strtotime("$name_current_day this week"));
//query to get count
foreach($name_list as $name){
//created in week
$data[$network->name.'_week'] = Info::select( DB::raw('DATE(`created_at`) as `date`'),DB::raw('COUNT(*) as `count`'))
->where('created_at', '>', $name_current_week)
->where('name',$name->f_name)
->groupBy('date')
->orderBy('date', 'DESC')
->lists('count', 'date');
}
When I run this query, I am not getting accurate results, Is this the cirrect way to get last 7 days records in Laravel.
You need to compare date() as well, and it's easier to use Carbon, though you don't need that. It's up to you.
EDIT: your question is a bit unclear, but it seems that you don't want week-old, but only current week's results.
Anyway, this will work for you:
// week old results:
// $fromDate = Carbon\Carbon::now()->subDays(8)->format('Y-m-d');
// $tillDate = Carbon\Carbon::now()->subDay()->format('Y-m-d');
// this week results
$fromDate = Carbon\Carbon::now()->subDay()->startOfWeek()->toDateString(); // or ->format(..)
$tillDate = Carbon\Carbon::now()->subDay()->toDateString();
Info::selectRaw('date(created_at) as date, COUNT(*) as count'))
->whereBetween( DB::raw('date(created_at)'), [$fromDate, $tillDate] )
->where('name',$name->f_name)
->groupBy('date')
->orderBy('date', 'DESC')
->lists('count', 'date');
You can use Carbon for this, which makes working with dates easier in Laravel. It's included with the framework. You can then do this:
$yesterday = Carbon::now()->subDays(1);
$one_week_ago = Carbon::now()->subWeeks(1);
foreach($name_list as $name){
//created in week
$data[$network->name.'_week'] = Info::select( DB::raw('DATE(`created_at`) as `date`'),DB::raw('COUNT(*) as `count`'))
->where('created_at', '>=', $one_week_ago)
->where('created_at', '<=', $yesterday)
->where('name',$name->f_name)
->groupBy('date')
->orderBy('date', 'DESC')
->lists('count', '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