Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Calendar Links Laravel Package

spatie/calendar-links

Generate “Add to calendar” links and ICS files for events. Supports Google Calendar, iCal/Apple Calendar, Outlook and more. Define title, start/end, description and location, then get shareable URLs or downloadable .ics content for your app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/calendar-links
    

    No additional configuration is required—just import and use.

  2. First Use Case: Generate a Google Calendar link for an event:

    use Spatie\CalendarLinks\Link;
    
    $link = Link::create(
        'Team Sync',
        now()->addHours(2), // Start time
        now()->addHours(3)  // End time
    )->google();
    

    Output: A clickable URL to add the event to Google Calendar.

  3. Where to Look First:

    • README for basic usage.
    • API Docs for method reference (e.g., google(), outlook(), ical()).
    • Examples for edge cases (e.g., all-day events, custom descriptions).

Implementation Patterns

Core Workflow

  1. Event Creation: Use Link::create() with:

    • Title (string): Event name.
    • Start/End (DateTime): Required for duration.
    • Optional: Location, description, attendees, etc.
      Link::create('Meeting', $start, $end)
          ->description('Project review')
          ->location('Zoom Room')
          ->attendee('user@example.com');
      
  2. Calendar Integration: Chain methods to target specific providers:

    $link->google();       // Google Calendar
    $link->outlook();      // Outlook
    $link->apple();        // Apple Calendar
    $link->ical();         // iCal (.ics file)
    
  3. Dynamic Generation: Generate links in Blade templates or controllers:

    // Blade
    <a href="{{ Link::create('Event', $start, $end)->google() }}">Add to Google</a>
    
    // Controller
    return response()->json(['google_link' => $link->google()]);
    
  4. Batch Processing: Loop through events to generate multiple links:

    foreach ($events as $event) {
        $links[$event->id] = [
            'google' => Link::create($event->title, $event->start, $event->end)->google(),
            'ical'   => Link::create($event->title, $event->start, $event->end)->ical(),
        ];
    }
    

Integration Tips

  • Laravel Routes: Create a dedicated route for calendar links:

    Route::get('/events/{event}/calendar/{provider}', function ($event, $provider) {
        $eventData = Event::findOrFail($event);
        $link = Link::create($eventData->title, $eventData->start, $eventData->end);
        return redirect()->to($link->$provider());
    });
    

    Example URL: /events/123/calendar/google.

  • API Endpoints: Return links as JSON for frontend frameworks:

    Route::get('/events/{event}/calendar-links', function ($event) {
        $eventData = Event::findOrFail($event);
        return [
            'google' => Link::create(...)->google(),
            'outlook' => Link::create(...)->outlook(),
        ];
    });
    
  • All-Day Events: Use allDay() for events without a time:

    Link::create('Conference', $date, $date)->allDay()->google();
    
  • Customization: Override default parameters (e.g., sprop for Google):

    $link->google(['sprop' => 'name:CustomName']);
    

Gotchas and Tips

Pitfalls

  1. Time Zone Handling:

    • Issue: Links may use UTC if DateTime isn’t timezone-aware.
    • Fix: Explicitly set timezone:
      $start = new DateTime('2023-12-25 10:00', new DateTimeZone('America/New_York'));
      
  2. URL Encoding:

    • Issue: Special characters in titles/descriptions may break links.
    • Fix: Use str_replace or urlencode for custom fields:
      $link->description(urlencode('Meeting with José & Co.'));
      
  3. Outlook/Google Quirks:

    • Outlook: May ignore end time if start is all-day.
    • Google: sprop parameters are optional but can affect rendering.
    • Workaround: Test links in target calendars before deployment.
  4. iCal File Generation:

    • Issue: .ics files may not render correctly if headers are missing.
    • Fix: Use Link::create()->ical()->get() to get raw content, then attach to a response:
      return response($link->ical()->get(), 200, [
          'Content-Type' => 'text/calendar',
          'Content-Disposition' => 'attachment; filename="event.ics"',
      ]);
      

Debugging

  • Validate Links: Use browser dev tools to inspect generated URLs. Compare against RFC 5545 for iCal. Example: Check if dates parameter in Google links uses YYYYMMDDTHHmmss format.

  • Log Raw Output: Temporarily log the generated link to debug:

    \Log::debug('Google Link:', ['url' => $link->google()]);
    

Extension Points

  1. Custom Providers: Extend the package by creating a new CalendarProvider class:

    namespace App\Providers;
    
    use Spatie\CalendarLinks\CalendarProvider;
    
    class CustomCalendar extends CalendarProvider {
        public function getUrl(): string {
            return 'https://custom-calendar.com/add?event=' . urlencode($this->getEventData());
        }
    }
    

    Register it in config/calendar-links.php under providers.

  2. Event Data Transformation: Override getEventData() in a custom class to modify payloads:

    class CustomLink extends Link {
        public function getEventData(): array {
            $data = parent::getEventData();
            $data['custom_field'] = 'value';
            return $data;
        }
    }
    
  3. Testing: Mock the Link class in tests:

    $mockLink = Mockery::mock(Link::class);
    $mockLink->shouldReceive('google')->andReturn('https://test.com');
    

Configuration Quirks

  • Default Provider: The package doesn’t enforce a default provider—always chain methods explicitly (e.g., ->google()).

  • iCal Formatting: Ensure DateTime objects are in the correct format for iCal (RFC 5545 compliant). Use format('Ymd\THis\Z') if needed.

  • Attendee Emails: Outlook/Google may validate email formats strictly. Test with real addresses during development.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport