Build a Dynamic Calendar with Livewire: A Step-by-Step Guide

Build a Dynamic Calendar with Livewire: A Step-by-Step Guide

Play this article

Livewire is a tool that helps developers build websites and web applications. It's like a set of building blocks that makes it easier and faster for developers to create websites that look and feel modern and dynamic.

The key benefit of Livewire is that it allows developers to build these dynamic websites without having to write as much complicated code. This means that developers can spend less time worrying about the technical details and more time focusing on the user experience and design of the website.

Today, Let's learn how can we build a calendar using Livewire.

To build a live calendar using Livewire in Laravel, you can follow these steps:

Step 1: Install Livewire First, you need to install Livewire in your Laravel application if you haven't already done so. You can do this using Composer by running the following command in your terminal:

composer require livewire/livewire

Step 2: Create a new Livewire component Next, create a new Livewire component that will handle the calendar functionality. You can do this by running the following command in your terminal:

php artisan make:livewire Calendar

This will create a new Livewire component called Calendar in the app/Http/Livewire directory.

Step 3: Define properties and methods Define some properties in the Calendar component to store the current month and year, as well as the events that are scheduled for the selected date. Add the following code to the Calendar component:

class Calendar extends Component
{
    public $month;
    public $year;
    public $events = [];

    public function mount()
    {
        $this->month = date('m');
        $this->year = date('Y');
    }

    public function getEventsForDate($date)
    {
        // Get the events for the selected date and store them in the $events property
    }

    public function render()
    {
        // Render the calendar view with the current month and year
    }
}

In the mount() method, we set the $month and $year properties to the current month and year.

The getEventsForDate() method will be used to fetch the events for the selected date and store them in the $events property.

The render() method will be used to render the calendar view with the current month and year.

Step 4: Create the view Next, create the calendar.blade.php view that will display the calendar and the events for the selected date. Add the following code to the calendar.blade.php file:

<div>
    <h2>{{ date('F Y', strtotime($year . '-' . $month . '-01')) }}</h2>

    <table>
        <thead>
            <tr>
                <th>Sun</th>
                <th>Mon</th>
                <th>Tue</th>
                <th>Wed</th>
                <th>Thu</th>
                <th>Fri</th>
                <th>Sat</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($calendar as $week)
                <tr>
                    @foreach ($week as $day)
                        <td wire:click="getEventsForDate('{{ $day['date'] }}')">{{ $day['day'] }}</td>
                    @endforeach
                </tr>
            @endforeach
        </tbody>
    </table>

    <div>
        @if (count($events) > 0)
            <h3>Events for {{ date('F j, Y', strtotime($selectedDate)) }}</h3>

            <ul>
                @foreach ($events as $event)
                    <li>{{ $event->title }}</li>
                @endforeach
            </ul>
        @endif
    </div>
</div>

This code displays the calendar for the selected month and year using a table element. The foreach loops are used to loop through the weeks and days of the calendar.

The wire:click directive is used to listen for clicks on each day of the calendar. When a day is clicked, it calls the getEventsForDate() method with the selected date as a parameter.

The if statement checks if there are any events for the selected date. If there are, it displays the events in an unordered list.

Step 5: Define the calendar data Define the data that will be used to generate the calendar. Add the following code to the Calendar component:

class Calendar extends Component
{
    public $month;
    public $year;
    public $events = [];

    public function mount()
    {
        $this->month = date('m');
        $this->year = date('Y');
    }

    public function getEventsForDate($date)
    {
        // Get the events for the selected date and store them in the $events property
    }

    public function render()
    {
        $calendar = [];

        $weeksInMonth = Carbon::createFromDate($this->year, $this->month)->weeksInMonth;

        for ($week = 1; $week <= $weeksInMonth; $week++) {
            $days = [];

            for ($day = 1; $day <= 7; $day++) {
                $date = Carbon::createFromDate($this->year, $this->month, 1)->addWeeks($week - 1)->addDays($day - 1);

                $days[] = [
                    'day' => $date->format('j'),
                    'date' => $date->format('Y-m-d'),
                ];
            }

            $calendar[] = $days;
        }

        return view('livewire.calendar', [
            'calendar' => $calendar,
            'selectedDate' => $this->selectedDate,
            'events' => $this->events,
        ]);
    }
}

In this code, we use the Carbon library to generate the calendar data. We start by getting the number of weeks in the current month using the weeksInMonth property.

We then loop through each week and each day of the week to generate an array of days for each week. We use the Carbon library to create a Carbon instance for each day, which allows us to easily format the day and date.

Finally, we return the calendar data, along with the selectedDate and events properties, to the view.

Step 6: Fetch the events for the selected date In the getEventsForDate() method, we need to fetch the events for the selected date and store them in the $events property. Here's an example code:

public function getEventsForDate($date)
{
    $this->selectedDate = $date;
    $this->events = Event::whereDate('start_time', $date)->get();
}

In this code, we set the $selectedDate property to the selected date and fetch the events for that date using the whereDate() method of the Event model. We then store the events in the $events property.

Step 7: Add styles Optionally, you can add some styles to the calendar to make it look better. Here's an example CSS code that you can use:

.calendar-container {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #ccc;
}

.calendar-container h2 {
    font-size: 24px;
    text-align: center;
}

.calendar-container table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
}

.calendar-container table th {
    padding: 10px;
    text-align: center;
    border: 1px solid #ccc;
}

.calendar-container table td
{ 
 padding: 10px; text-align: center; 
 border: 1px solid #ccc; 
} 
.calendar-container table td.today { 
background-color: #fff6d5; 
}

.calendar-container table td:not(.disabled):hover { cursor: pointer; background-color: #f1f1f1; 
}

.calendar-container table td.disabled { color: #ccc;
}

In this code, we define some basic styles for the calendar container, the header, the table, and the table cells. We also define a style for the current date cell and a hover effect for the clickable cells.

Step 8: Display the events Finally, we need to display the events for the selected date in the calendar. We can do this by adding the following code to the render() method:

return view('livewire.calendar', [ 'calendar' => $calendar, 'selectedDate' => $this->selectedDate, 'events' => $this->events, ]);

And adding the following code to the index.blade.php view:


@if (count($events) > 0) <ul> @foreach ($events as $event) <li>{{ $event->name }}</li> @endforeach </ul> @endif

In this code, we check if there are any events for the selected date, and if there are, we display them in an unordered list.

That's it! You now have a working live calendar in Laravel using Livewire. You can customize this code further to add more features, such as the ability to add and edit events.

Did you find this article valuable?

Support Laravel Tips & Tutorials - KeyTech Blog by becoming a sponsor. Any amount is appreciated!