Create Events in Laravel 10 with Fullcalendar and AJAX

Last Updated on by in Laravel

Laravel fullcalendar crud events tutorial; In this tutorial, we will profoundly simplify how to add FullCalendar in Laravel app to create and delete events using the Fullcalendar JavaScript event calendar plugin.

FullCalendar is a great, powerful, and lightweight JavaScript calendar plugin primarily used to create dynamic, draggable event calendars on modern web applications.

FullCalendar package supports jQuery AJAX and manages your events smoothly, and you can spruce it up visually because it offers easy customization.

This comprehensive guide, step by step, explains how to add and integrate FullCalendar in Laravel not only but also how to use FullCalendar in the Laravel app.

How to Create Laravel 10 Fullcalendar CRUD Events

  • Step 1: Create Laravel App
  • Step 2: Connect to Database
  • Step 3: Set Up Migration and Model
  • Step 4: Generate and Configure Controller
  • Step 5: Create and Add Routes
  • Step 6: Create Blade View
  • Step 7: Run Development Server

Create Laravel App

It would be best if you had composer configured on your system, and this allows you to install the new laravel application. However, you may ignore this step if the app is already created.

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

Make sure to get into the app folder:

cd full-calendar-demo

Connect to Database

After you entered the inside app, the first thing we do is open the .env file and add the database details in the ENV configuration file to connect the laravel app to the database.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db
DB_USERNAME=root
DB_PASSWORD=

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Set Up Migration and Model

We need to create the events table into the database and add some values related to events, so execute the following command to generate the migration and model file.

php artisan make:model CrudEvents -m

Next, you need to open the app/Models/CrudEvents.php file and create a $fillable array and define the crud events values.

<?php

namespace App\Models;

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

class CrudEvents extends Model
{
    use HasFactory;
    
    protected $fillable = [
        'event_name', 
        'event_start', 
        'event_end'
    ];    
}

Further, add event_name, event_start and event_end values inside the 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 CreateCrudEventsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('crud_events', function (Blueprint $table) {
            $table->id();
            $table->string('event_name');
            $table->date('event_start');
            $table->date('event_end');            
            $table->timestamps();
        });
    }

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

Plus, propel the migration into the database, so run the command:

php artisan migrate

Generate and Configure Controller

We need to create a new calendar to handle create, read, update and delete events, run the given below command to generate a new controller file.

php artisan make:controller CalenderController

Then, create two functions inside the app\Http\Controllers\CalenderController.php file, this will set up view and perform CRUD operations for fullcalendar events.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\CrudEvents;

class CalenderController extends Controller
{

    public function index(Request $request)
    {
        if($request->ajax()) {  
            $data = CrudEvents::whereDate('event_start', '>=', $request->start)
                ->whereDate('event_end',   '<=', $request->end)
                ->get(['id', 'event_name', 'event_start', 'event_end']);
            return response()->json($data);
        }
        return view('welcome');
    }
 

    public function calendarEvents(Request $request)
    {
 
        switch ($request->type) {
           case 'create':
              $event = CrudEvents::create([
                  'event_name' => $request->event_name,
                  'event_start' => $request->event_start,
                  'event_end' => $request->event_end,
              ]);
 
              return response()->json($event);
             break;
  
           case 'edit':
              $event = CrudEvents::find($request->id)->update([
                  'event_name' => $request->event_name,
                  'event_start' => $request->event_start,
                  'event_end' => $request->event_end,
              ]);
 
              return response()->json($event);
             break;
  
           case 'delete':
              $event = CrudEvents::find($request->id)->delete();
  
              return response()->json($event);
             break;
             
           default:
             # ...
             break;
        }
    }
}

Create and Add Routes

Now that controller has been setup, next move to routes/web.php file, in this file we need to use the CalenderController to create the routes.

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

Route::get('calendar-event', [CalenderController::class, 'index']);
Route::post('calendar-crud-ajax', [CalenderController::class, 'calendarEvents']);

Create Blade View

Lastly, we need to show the full calendar in the laravel blade view file, make the jQuery AJAX request to create, read, update and delete events. For that, we take the help of our full calendar APIs that we have created in the previous step.

Open resources/views/welcome.blade.php file and replace the entire code with the suggested below code:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Create Fullcalender CRUD Events in Laravel</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" />
</head>

<body>

    <div class="container mt-5" style="max-width: 700px">
        <h2 class="h2 text-center mb-5 border-bottom pb-3">Laravel FullCalender CRUD Events Example</h2>
        <div id='full_calendar_events'></div>
    </div>

    {{-- Scripts --}}
    <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>

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

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

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

            var calendar = $('#full_calendar_events').fullCalendar({
                editable: true,
                editable: true,
                events: SITEURL + "/calendar-event",
                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_name = prompt('Event Name:');
                    if (event_name) {
                        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: SITEURL + "/calendar-crud-ajax",
                            data: {
                                event_name: event_name,
                                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_name,
                                    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: SITEURL + '/calendar-crud-ajax',
                        data: {
                            title: event.event_name,
                            start: event_start,
                            end: event_end,
                            id: event.id,
                            type: 'edit'
                        },
                        type: "POST",
                        success: function (response) {
                            displayMessage("Event updated");
                        }
                    });
                },
                eventClick: function (event) {
                    var eventDelete = confirm("Are you sure?");
                    if (eventDelete) {
                        $.ajax({
                            type: "POST",
                            url: SITEURL + '/calendar-crud-ajax',
                            data: {
                                id: event.id,
                                type: 'delete'
                            },
                            success: function (response) {
                                calendar.fullCalendar('removeEvents', event.id);
                                displayMessage("Event removed");
                            }
                        });
                    }
                }
            });
        });

        function displayMessage(message) {
            toastr.success(message, 'Event');            
        }

    </script>

</body>

</html>

Run Development Server

Head over to the terminal, open the terminal window next, type the php artisan command with serve tag to start the laravel development server.

php artisan serve

Open any browser, type the recommended url on the address bar and test the fullcalendar crud events app.

http://127.0.0.1:8000/calendar-event

FullCalendar Example using Ajax in Laravel

Conclusion

The laravel fullcalendar crud event tutorial is finished; this example described creating an event crud app using the FullCalendar plugin.

We created a simple table in the database with the event name, event start date, and event end date and store and manage our events in conjunction with the MySQL database.

We hope you have liked this tutorial and will share it with others.