Site Admin
Site Admin Founder of MeaningArticles
2240 Views

Create event in Laravel 8 using Fullcalendar and jQuery AJAX step by step with example

Hello Dev.

Laravel 8 fullcalendar CRUD events article, In this article, we are able to profoundly simplify how to add FullCalendar in Laravel 8 application to create and delete events the usage of Fullcalendar JavaScript event calendar plugin.

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

FullCalendar package helps jQuery AJAX and manages your events smoothly, and you could spruce it up visually as it offers easy customization. This comprehensive guide, little by little, explains the way to add and integrate FullCalendar in Laravel now not only however additionally the way to use FullCalendar inside the Laravel application.

So let's start the lesson...


How to create Laravel 8 Fullcalendar CRUD events

Here equal step for create laravel Fullcalendar CRUD applications follow the below steps:
- Create Laravel App
- Configuration of Database
- Set Up Migration and Model
- Generate and Configure Controller
- Create and Add Routes
- Create Blade View
- Run Development Server


Step 1: Create Laravel App

First of all we want to get clean and new Laravel eight version application the use of bellow command, now open your terminal OR command prompt and then fire bellow command and run it(However, you may ignore this step if the app is already created):

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

Ensure to get into the app folder:

cd full-calendar-demo


Step 2: Configuration of Database

Second step, we configure database like database name, username, password and many others for CRUD utility of laravel. permit's open .env file and fill full details same as bellow:
.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)


Step 3: Set Up Migration and Model

We want to create the events table into the database and add some values related to events, so execute the subsequent 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.
CrudEvents.php

<?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 within the database/migrations/create_crud_events_table.php file.
create_crud_events_table.php

<?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


Step 4: Generate and Configure Controller

We want 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 could installation view and perform CRUD operations for fullcalendar events.
CalenderController.php

<?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;
        }
    }
}


Step 5: Create and Add Routes

Now that controller has been setup, subsequent pass to routes/web.php file, on this file we need to apply the CalenderController to create the routes.
web.php

<?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']);


Step 6: Create Blade View

Finally, we need to show the entire 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 inside the preceding step.

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

<!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 - meaningarticles.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/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 - meaningarticles.com</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>


Step 7: Run Development Server

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

php artisan server

Open any browser, kind the endorsed url on the address bar and check the fullcalendar crud events app.

http://127.0.0.1:8000/calendar-event

I hope it assists you, thanks for visiting my article if you like my article then share it with your friends on the social media platform.

Happy Coding.....