Home  >  Q&A  >  body text

Retrieve data from Laravel model and generate Spatie/Icalendar

I tried retrieving the data from the model and then rewriting it into the appropriate format for the Spatie Icalendar, but it didn't work since there were multiple events and not just a single event.

I tried many different solutions but didn't find one that worked.

How would you iterate over the many events in Spatie?

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

I want to iterate over all calendar events and create an array for Spatie.

It should end in ICAL format, extractable for normal calendars.

P粉312195700P粉312195700300 days ago460

reply all(1)I'll reply

  • P粉317679342

    P粉3176793422024-01-17 11:45:21

    There are a lot of inconsistencies in the code, which I think makes things more difficult. Classes naming events as properties, inconsistent naming conventions, pluralization models (I know, class is a reserved keyword), etc.

    Just loop 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 thought it needed an end time, so I added an hour. The start_time on the model should be added to the $dates array to be converted to a Carbon object. Instead of using a for loop, I used collection methods to create similar logic, read them here. This is the type returned by the query builder.

    reply
    0
  • Cancelreply