Add Events in Laravel 9 with FullCalendar & AJAX Tutorial

Do you want to integrate full-calendar in laravel? You have a goal to create dynamic events in laravel, then worry not?

This ultimate guide will teach you how to implement an event calendar in the laravel app using the pragmatic FullCalendar library from absolute scratch.

In this Laravel Ajax calendar example, we will specifically use AJAX.

It offers an effortless way to process the requests in background; AJAX handles requests asynchronously and doesn’t reload the entire page while handling the requests.

We will answer all types of questions like how to add an event to Full Calendar on click and how to use the calendar component in laravel to form events.

After going through every step of this tutorial, you will be understood how to create an event calendar, add and delete events using the calendar and store those events in the database using jQuery Ajax.

Let’s get started.

How to Integrate FullCalendar in Laravel 9 App?

  • Step 1: Download Laravel Project
  • Step 2: Make Database Connection
  • Step 3: Create Model and Migration
  • Step 4: Set Up Event Controller
  • Step 5: Register Routes
  • Step 6: Add Event Calendar Widget in View
  • Step 7: View App in Browser

Download Laravel Project

You must have a laravel app ready to add events dynamically in laravel;

composer create-project --prefer-dist laravel/laravel laravel-full-calendar-example

It is easy to download a new app; once the app is ready, head over to the project.

cd laravel-full-calendar-example

Make Database Connection

Update .env configuration file, you can configure database connection by inserting database name, username and password in this file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=db_username
DB_PASSWORD=db_password

Create Model and Migration

Model and migration files help you set the basic structure of the table which stays in your database, use given command to generate the model and migration files.

php artisan make:model CalendarEvent -m

The values you define in the up() functions’ create method, decides what will be the table values. For our events table, we have added the given values in database/migrations/create_crud_events_table.php file.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCalendarEventsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('calendar_events', function (Blueprint $table) {
            $table->id();
            $table->string('event_title');
            $table->date('event_start');
            $table->date('event_end');             
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('calendar_events');
    }
}

Next, add the similar values inside the fillable array in app/Models/CalendarEvent.php file .

The $fillable property is an array holding all the table fields that directly refer to the table values in the DatabaseDatabase. It communicates with the model and creates a new record in the Database in an eloquent style.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CalendarEvent extends Model
{
    use HasFactory;

    protected $fillable = [
        'event_title', 
        'event_start', 
        'event_end'
    ];
}

All has been set where it belongs; run command to invoke the migration process, but make sure to start the PHP server.

php artisan migrate

Set Up Event Controller

Further, create a new controller, you can do it by running the given command.

php artisan make:controller EventController

If you look into the Controllers folder, you can see a new file. In general, it is a single class, which can be used to define the various functions to handle dynamic calendar events in laravel.

Update app\Http\Controllers\EventController.php file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\CalendarEvent;

class EventController extends Controller
{
    public function index(Request $request)
    {
        if($request->ajax()) {  
            $data = CalendarEvent::whereDate('event_start', '>=', $request->start)
                ->whereDate('event_end',   '<=', $request->end)
                ->get(['id', 'event_title', 'event_start', 'event_end']);
            return response()->json($data);
        }
        return view('calendar');
    }
 

    public function manageEvents(Request $request)
    {
        switch ($request->type) {
           case 'create':
              $calendarEvent = CalendarEvent::create([
                  'event_title' => $request->event_title,
                  'event_start' => $request->event_start,
                  'event_end' => $request->event_end,
              ]);
 
              return response()->json($calendarEvent);
             break;
  
           case 'edit':
              $calendarEvent = CalendarEvent::find($request->id)->update([
                  'event_title' => $request->event_title,
                  'event_start' => $request->event_start,
                  'event_end' => $request->event_end,
              ]);
 
              return response()->json($calendarEvent);
             break;
  
           case 'delete':
              $calendarEvent = CalendarEvent::find($request->id)->delete();
  
              return response()->json($calendarEvent);
             break;
             
           default:
             break;
        }
    }
}

Register Routes

The functions created in the controller are executed through routes, therefore get into routes/web.php and update the provided code.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EventController;

/*
|--------------------------------------------------------------------------
| Route Definitions
|--------------------------------------------------------------------------
*/

Route::get('/show-event-calendar', [EventController::class, 'index']);
Route::post('/manage-events', [EventController::class, 'manageEvents']);

Create CRUD Events in Laravel

Further, head over to the views folder within the resource directory, create a calendar.php file in this file import the CSS, JS and other resources to integrate the calendar in laravel, most importantly for creating dynamic crud events.

Update resources/views/calendar.blade.php file.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Laravel Full Calendar Integration Example</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.css" rel="stylesheet"/>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet"/>
    {{-- javascript --}}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>    
</head>

<body>

    <div class="container mt-4">
        <h2 class="mb-5">Laravel Calendar CRUD Events Example</h2>
        <div id='fullCalendar'></div>
    </div>

    <script>
        $(document).ready(function () {

            var endpoint = "{{ url('/') }}";

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            var calendar = $('#fullCalendar').fullCalendar({
                editable: true,
                editable: true,
                events: endpoint + "/show-event-calendar",
                displayEventTime: true,
                eventRender: function (event, element, view) {
                    if (event.allDay === 'true') {
                        event.allDay = true;
                    } else {
                        event.allDay = false;
                    }
                },
                selectable: true,
                selectHelper: true,
                select: function (event_start, event_end, allDay) {
                    var event_title = prompt('Event Name:');
                    if (event_title) {
                        var event_start = $.fullCalendar.formatDate(event_start, "Y-MM-DD HH:mm:ss");
                        var event_end = $.fullCalendar.formatDate(event_end, "Y-MM-DD HH:mm:ss");
                        $.ajax({
                            url: endpoint + "/manage-events",
                            data: {
                                event_title: event_title,
                                event_start: event_start,
                                event_end: event_end,
                                type: 'create'
                            },
                            type: "POST",
                            success: function (data) {
                                displayMessage("Event created.");

                                calendar.fullCalendar('renderEvent', {
                                    id: data.id,
                                    title: event_title,
                                    start: event_start,
                                    end: event_end,
                                    allDay: allDay
                                }, true);
                                calendar.fullCalendar('unselect');
                            }
                        });
                    }
                },
                eventDrop: function (event, delta) {
                    var event_start = $.fullCalendar.formatDate(event.start, "Y-MM-DD");
                    var event_end = $.fullCalendar.formatDate(event.end, "Y-MM-DD");

                    $.ajax({
                        url: endpoint + '/manage-events',
                        data: {
                            title: event.event_title,
                            start: event_start,
                            end: event_end,
                            id: event.id,
                            type: 'edit'
                        },
                        type: "POST",
                        success: function (response) {
                            displayMessage("Event updated");
                        }
                    });
                },
                eventClick: function (event) {
                    var removeEvent = confirm("Really?");
                    if (removeEvent) {
                        $.ajax({
                            type: "POST",
                            url: endpoint + '/manage-events',
                            data: {
                                id: event.id,
                                type: 'delete'
                            },success: function (response) {
                                calendar.fullCalendar('removeEvents', event.id);
                                displayMessage("Event deleted");
                            }
                        });
                    }
                }
            });
        });

        function displayMessage(message) {
            toastr.success(message, 'Event');            
        }
    </script>
</body>
</html>

View App in Browser

The coding part has been done, now comes the time to start the app and view the app in the browser; here is the command to run the app.

php artisan serve

Paste the provided url browser’s address bar to view the app.

http://127.0.0.1:8000/show-event-calendar

Laravel fullcalendar ajax

Conclusion

In this detailed guide, we learned how to create a basic laravel calendar event application. A user can create, read, delete events using the calendar widget and store the created events directly in the database with the help of AJAX.

We used a full-calendar package and implement this library in laravel to create a laravel calendar app, so that’s all we had for you. Have a good day.