skip to Main Content

My code

I’m trying to retrieve data from a model, then rewriting it to the appropriate format for the Spatie Icalendar, but then it doesn’t work, because of multiple events and not only a single one.

I have tried many different solutions, but didn’t find one that’s working.

Please, how would you iterate over the many events in the Spatie?

Spatie Documentation: https://github.com/spatie/icalendar-generator

I would like to iterate through all the calendar events, creating an array for the spatie.

It should end up in an ICAL format, that’s extractable for normal calendars.

2

Answers


  1. A lot of inconsistencies in the code, that i think makes it way harder than it have to be. Classes named events as properties, inconsistent naming conventions, model in plural (i know, class is a reserved keyword) etc.

    Simply loop over the events and add the model data one by one to the spatie package.

    $calendar = Calendar::create($iCalendar->name);
    
    $events->each(function (Classes $event) {
        $calendar->event(Event::create($event->class_type === 1 ? 'Teoritime' : 'Køretime')
            ->startsAt($event->start_time)
            ->endsAt($event->start_time->addHour())
        )  
    });
    
    dd($calendar->get());
    

    I would assume it requires an end time, so i added one hour. start_time on the model should be added to the $dates array to be casted to a Carbon object. Instead of doing for loops, i use the collection methods to create similar logic, read about them here. Which is the type that the query builder returns.

    Login or Signup to reply.
  2. The documentation states you can add an array of events to a calendar:

    After creating your event, it should be added to a calendar. There are multiple options to do this.

    Here are some examples in pseudo-code, adapt to your real objects:

    Add multiple events:

    $caledar->event($event_1)
            ->event($event_2)
            ->event($event_99)
            ...
    

    Or better yet, add an array of events:

    $events = [];
    
    foreach(Classes::all() as $class) {
        $events[] = Event::create($class->type)->startsAt($class->start_time);
    }
    
    $calendar->event($events);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search