Scope to get all records that have anniversary within the next two weeks Based on a date field, I would like to retrieve all records that have an anniversary within the next two weeks using a query scope.
I can get all records where today is the anniversary using the following:
public function scopeTodayIsAnniversary($query)
{
return $query->whereMonth('started_on', Carbon::now())
->whereDay('started_on', Carbon::now());
}
between now and 2 weeks from now
->whereBetween('started_on', [now(), now()->addWeeks(2)])
Thanks, but this doesn't work for the use case of an anniversary, i.e. day and month are the same or within two weeks, but the year can be different.
I'm not sure what you mean. if "today" is 12/20/2019, it would check between that date and 1/3/2020, 2 weeks later?
Say I have seven records with a date fields populated as below:
2017-02-14
2017-02-28
2018-02-16
2018-02-22
2018-03-08
2018-04-17
2018-05-02
I'd like a scope that returns the top four records as they have anniversaries that are coming up within the next two weeks.
You need to go by days, ignore year. Like dealing with angles.
359 degrees + 10 degrees = 369 but what is angle?
369 - 360 = 9 degrees
Do something similar for the days, I don't know about a leap year.
Would't hurt to have a column updated in table for anniversary.
Will take a bunch of logic to work out. I used to also program cnc cutters.
Yes this would have to be done using other date functions that eloquent doesn't provide (you'd have to do raw statements). The leap year is an issue, but mysql datetime functions handle that. I'd have to play with that later. Sorry, I don't have a quick/easy answer for this.
The following code is an example provided by Jonathan Reinick at Laracon 2018 during his talk about Eloquent
Birthdays this week
public function scopeWhereBirthdayThisWeek($query)
{
$start = Carbon::now()->startOfWeek();
$end = Carbon::now()->endOfWeek();
$dates = collect(new \DatePeriod($start, new \DateInterval('P1D'), $end))->map(function ($date) {
return $date->format('md');
});
return $query->whereNotNull('birth_date')->whereIn(\DB::raw("to_char(birth_date, 'MMDD')"), $dates);
}
Please sign in or create an account to participate in this conversation.