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

oliverbusk's avatar

Carbon - Get past and next 4 weeks

I am trying to show the previous 4 weeks and next 4 weeks (in numbers), like below:

Current week: 42

Week: 38
Week: 39
Week: 40
Week: 41
Week: 42
Week: 43
Week: 44
Week: 45
Week: 46

This is the code I have so far:

$this->week = '42'

$date = Carbon::now();
$date->setISODate(date('Y', time()), $this->week);

$start = $date->copy()->subWeeks(4)->week();
$end = $date->copy()->addWeeks(4)->week();

$weeks = CarbonPeriod::create($start, '1 week', $end);

And then in my blade view, I have this:

@foreach($weeks as $week)
              <a href="?week={{$week}}">
                        <div>{{\Carbon\Carbon::create($week)->week()}}</div>
              </a>
@endforeach

However, above prints out the following 38 weeks.

Any idea on how I can print out the past 4 and next 4 weeks?

0 likes
1 reply
Snapey's avatar
Snapey
Best Answer
Level 122

sub 4 weeks to get week number from 4 weeks ago

in loop, iterate exactly 9 times, each time output the week number from Carbon then add a week to the carbon value.

Doing it this way ensures that it rolls to previous or next year correctly

1 like

Please or to participate in this conversation.