0

So I've succeeded to make a calendar display for the current month. This time, I want to show event details for a specific date. I'm not sure how to get the $event data where $event == $date.

This is the controller. I have event and dates to be used in the view:

$event = Event::where("started_at", '>=', Carbon::now()->subDays(30)->toDateTimeString())
         ->orderBy("started_at", "asc")
         ->first();
$data["event"] = $event;
$data["month"] = Carbon::now()->month;
$data["dates"] = range('1', date('t'));
return view('event.all', $data);

This is the event.all view:

@foreach($dates as $date)
    <div class="seven-cols">
        <div class="titlehead">
            <h6>{{$date}}</h6>
            <h6 style="color: lightgrey;">{{date("D", mktime(0, 0, 0, $month, $date))}}</h6>
            <div style=" ">{{$eventdate = date('d',strtotime(@$event->started_at))}}</div>
            @if($event->started_at == $date)
                <div>Test</div>
            @endif
        </div>
    </div>
@endforeach

What I got for this code:

enter image description here

M0nst3R
  • 5,186
  • 1
  • 23
  • 36
Steve Ruru
  • 143
  • 1
  • 3
  • 11

1 Answers1

0

As this other answer suggests I would use CarbonPeriod (or create a range with a loop if CarbonPeriod not available for you) and then collect the events for each date at the same time.

As a good practice, we should avoid keeping too much logic inside the templates and therefore build as much as we can of the content before actually building the template itself.

Using your example, and assuming that you only want to show one event for each day we could have something like this:

(Not tested code though)

$startDate = Carbon::now()->subDays(30)->toDateTimeString();
$endDate = Carbon::now()->toDateTimeString();

// Narrow down the list from the database
$events = Event::whereBetween("started_at", [$startDate, $endDate])
    ->orderBy("started_at")
    ->get();

$data = CarbonPeriod::create(
    $startDate, 
    $endDate
)
->map(function(Carbon $date) {
    $event = $events
       ->where("started_at", $date->toDateTimeString())
        ->first();

    return [
        "date" => $date,
        "event" => $event,
    ];
});

return view('event.all', $data);

And in the template:

@foreach($data as $day)
    <div class="seven-cols">
        <div class="titlehead">
            <h6>{{$day["date"]->day}}</h6>
            <h6 style="color: lightgrey;">{{$day["date"]->format("D")}}</h6>
            <div style=" ">{{$day["date"]->format("d")}}</div>
                @if(!is_null($day["event"]))
                    <div>{{$day["event"]->someTextField}}</div>
                @endif
            </div>
        </div>
    </div>
@endforeach

I hope it helps!