Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

trifek's avatar

Displaying events 3 years ahead

HI, I make planner "event list". I have model:

class Event extends Model
{
    use Notifiable;

    protected $guarded = ['id'];

    protected $fillable = [
        'title',
        'description',
        'count',
        'date',
        'notification_date',
        'notification_sent_at'
    ];

    protected $dates = [
        'created_at',
        'updated_at'
    ];

    public function routeNotificationForMail()
    {
        return $this->email;
    }

}

title - this title my event, description - description about my event, count - number every how many days the event is repeated notification_date - date from when we display the event

Now when I make:

Event::all()

Return me only records from DB. This is understandable. However, I need to list 3 years ahead based on count and notification_date.

For example, notification_date = 7/1/2023 and count = 2 I would like to get a list 01.07.2023, 03.07.2023, 05.07.2023, 07.07.2023, 09.07.2023, ..... xx.xx.2026.

How can I make it?

Please help me

0 likes
2 replies
LaryAI's avatar
Level 58

To list events 3 years ahead based on the count and notification_date, you can use a loop to generate the dates and filter them based on the given criteria. Here's an example solution in PHP:

// Assuming you have the notification_date and count values from the database
$notificationDate = '7/1/2023';
$count = 2;

// Convert the notification_date to a DateTime object
$startDate = DateTime::createFromFormat('m/d/Y', $notificationDate);

// Create an empty array to store the generated dates
$dates = [];

// Loop through 3 years (365 days * 3)
for ($i = 0; $i < 365 * 3; $i++) {
    // Add the count days to the start date
    $date = $startDate->add(new DateInterval("P{$count}D"));

    // Add the date to the array
    $dates[] = $date->format('F j, Y');
}

// Print the generated dates
print_r($dates);

This code will generate an array of dates starting from the notification_date and incrementing by the count value. You can modify the code to fit your specific needs and integrate it into your Laravel application.

ramonrietdijk's avatar
Level 30

I think a CarbonPeriod is very powerful in this situation.

use Carbon\Carbon;
use Carbon\CarbonPeriod;

$startDate = Carbon::parse('7/1/2023');
$endDate = $startDate->copy()->addYears(3);
$days = 2;

$period = CarbonPeriod::since($startDate)->days($days)->until($endDate);

foreach ($period as $date) {
	echo $date->toDateString() . PHP_EOL;
}

// 2023-07-01
// 2023-07-03
// 2023-07-05
// 2023-07-07
// 2023-07-09
// ...
1 like

Please or to participate in this conversation.