How to add days in querying date? laravel - php

How can we add days in the date that we're querying using laravel eloquent?
Something like this:
Post::where('created_at + 7 days', now()->toDateTimeString())
->where('created_at', '<', now()->toDateTimeString())
->get();
My logic is like this one
today >= created_at && today <= created_at + 4
Is there some correct syntax to achieve this one?

One of the ways to compare from date time is using the calculated Carbon like below:
Post::where('created_at', '>=', now()->addDays(4)->toDateTimeString()
->get();
It will display only posts which have created_at greater than 4 days from today.
For date range filter, you can use between scope like:
$startDate = now()->subDays(4)->toDateString();
$endDate = now()->toDateString();
$filteredPosts = Post::whereBetween('created_at', [$startDate, $endDate])->get();
For more information about filter, you could visit Laravel Query Builder

You can use whereDate method:
Post::whereDate('created_at', 'like', now()->subDays(4))->get();
or
Post::whereDate('created_at', '>=', now()->subDays(4))->get();

Related

Laravel query builder inject column value into Carbon query

I've got a query that I'm running in my project on a model called Domain, it returns all domains where the status column of a domain matches complete and a date column is before or equal to a specific set of days.
I've recently refactored the model columns and have included a new column called domain_alert_period which is an integer column that holds a value in days, I need to somehow target this column and put it in replace of my existing 30 so that the user is able to control the number of days prior to getting an alert.
What am I missing from this to achieve this?
return Domain::where('status', 'complete')
->where(function ($sql) {
$sql->where('domain_expires_on', '>', Carbon::now()->subDays(2)) // 2 days after expiry
->where('domain_expires_on', '<', Carbon::now()->addDays(30)); // 30 days before expiry
})
->get();
I believe you can use whereRaw() in your clause to use raw DB expressions, If its MySQL you can use DATE_ADD method with your column value for comparision
$sql->where('domain_expires_on', '>', Carbon::now()->subDays(2)) // 2 days after expiry
->whereRaw('domain_expires_on < DATE_ADD(NOW(), INTERVAL domain_alert_period DAY)');
A mysql DATE_SUB function should be used to subtract days from a domain_expires_on date. so that will be a date you should start an alert from
And then match a current date is greater or equal to that alert date
$query = $this->model
->whereRaw('CURDATE() <= DATE_ADD(`domain_expires_on` , INTERVAL 2 DAY)') // till 2 days after expiry
->whereRaw('CURDATE() >= DATE_SUB(`domain_expires_on` , INTERVAL domain_alert_period DAY)')
->get();
If i understand your question correctly what you can do is use use ($var) in your query to replace 30
$start=1; //you can also take date from user for between like `date_from` and `date_to` and parse them with Carbon insted of adding or substracting days from now()
$end=30;
return Domain::where('status', 'complete')
->where(function ($sql) use ((int) $start,(int) $end) {
$sql->whereDate('domain_expires_on', '>', Carbon::now()->subDays($start)->toDateString())
->whereDate('domain_expires_on', '<', Carbon::now()->addDays($end)->toDateString());
})
->get();
Also if you are storing domain_expires_on only as the date you should format the carbon date to match your database format.
above method will work for $table->date('domain_expires_on'); and $table->dateTime('domain_expires_on');

Retrieve all rows from the last possible 3 years (Laravel + Eloquent)

I'm trying to get all the rows I can in a Model, however it must be the last 3 possible years, as if I have a result in the year 2020 but nothing in the year 2019 then it must search in 2018, 2017, but if I had a result in 2019 then it must search only for the results in 2018.
I've already gotten the hang of whereBetween, however I don't get any results from the database using the following query:
$year = $request->all();
$fromDate = $year['yearFrom'];
$toDate = $year['yearTo'];
return Tipico::whereBetween(
DB::raw('date(created_at)'), [$fromDate, $toDate]
)
->get();
As you can see, I get the year from a post method which gives me the initial and finish year, however it doesn't validate the information I'm searching for, whats the best way to do it?
Use Carbon to create your dates:
$fromDate = Carbon::createFromDate($year['yearFrom'], 1, 1)->startOfDay();
$toDate = Carbon::createFromDate($year['yearTo'], 12, 31)->endOfDay();
Then in your query, created_at is already a datetime, so:
return Tipico::whereBetween('created_at', [$fromDate, $toDate])->get();
Remember to include Carbon in your Class at the top:
use Illuminate\Support\Carbon;
or only
use Carbon\Carbon;
To get the data from the past 3 years, one option would be to run a query to see what years have the data you need.
So, let's use the yearTo as reference to his and select the top 3 years with data:
$years = Tipico::select(\DB::raw('YEAR(created_at) as years'))
->where('created_at', '<=', $toDate)
->distinct()
->orderByRaw('YEAR(created_at) DESC')
->limit(3)
->get();
Now in $years you will have the 3 years. Now you can run the query with this years as parameter:
return Tipico::whereIn(\DB::raw('YEAR(created_at)'), $years)->get();
*Not sure if you can pass $years directly or need to transform to array. Take a look.

PHP Carbon / Laravel Eloquent - Check if DateTime value is for the current day

I am working on a booking system and need to select only the records where a certain field is for today. Not today and in the future, but only today.
The query currently is:
$advancedBookings = Booking::where('type', 2)
->whereNull('estimated_booking_time')
->where('requested_booking_time', ?????);
$advancedBookings->get();
The requested_booking_time is the field that I wish to be checked, the date stored is in this format:
2017-08-23 08:00:00
So I want to only select rows that are on the same day as the current day.
As i understand, you want that records which is created today; then just get the today's date.
$today = date("Y-m-d");
now your query is like this.
$advancedBookings = Booking::where('type', 2)
->whereNull('estimated_booking_time')
->where('requested_booking_time', $today)->get();
You can use whereDate and format your dates with Carbon:
$advancedBookings = Booking::where('type', 2)
->whereNull('estimated_booking_time')
->whereDate('requested_booking_time', '=' , Carbon::today()->toDateString());
$advancedBookings->get();
Or format the your date before the query with Carbon.
You should try this:
$advancedBookings = Booking::where('type', 2)
->whereNull('estimated_booking_time')
->whereDate('requested_booking_time', '=', date('Y-m-d'))
->get();

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

Categories