Laravel 10 FullCalendar Ajax CRUD Tutorial Example

https://onlinewebtutorblog.com/laravel-10-fullcalendar-ajax-crud-tutorial-example/

Laravel 10 FullCalendar Ajax CRUD Tutorial Example

March 6, 2023 by Sanjay Kumar

Table of Contents

Share this Article

Reading Time: 9 minutes 73 Views

Inside this article we will see the concept i.e Laravel 10 FullCalendar Ajax CRUD Tutorial Example. Article contains the classified information i.e How to work with FullCalendar in laravel 10 to handle data.

FullCalendar is a JavaScript library that provides a full-featured calendar interface for displaying and interacting with events and schedules. It is designed to be highly customizable and easy to integrate into web applications.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

$ composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

$ php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

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

Create Migration

Open project into terminal and run this command to create migration file.

$ php artisan make:migration create_events_table

It will create 2023_03_04_031027_create_events_table.php file inside /database/migrations folder. Open migration file and write this following code into it.

The code is all about for the schema of events table.

xxx_create_events_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->id();
            $table->string('title', 50);
            $table->date('start');
            $table->date('end');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('events');
    }
};

Run Migration

Back to terminal and run this command.

$ php artisan migrate

It will create events table inside database.

Next,

Create Model

We will create model. Back to terminal and run this command.

$ php artisan make:model Event

It will create a model file Event.php inside /app/Models folder. Open up the file and write this code into it.

Event.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
    use HasFactory;
    protected $fillable = [
        'title', 'start', 'end'
    ];
}

Create Controller

Open project into terminal and run this command into it.

$ php artisan make:controller FullCalendarController

It will create FullcalendarController.php file inside /app/Http/Controllers folder. Open controller file and write this code into it.

FullCalendarController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Event;
class FullCalendarController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = Event::whereDate('start', '>=', $request->start)
                ->whereDate('end',   '<=', $request->end)
                ->get(['id', 'title', 'start', 'end']);
            return response()->json($data);
        }
        return view('fullcalendar');
    }
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function ajax(Request $request)
    {
        switch ($request->type) {
            case 'add':
                $event = Event::create([
                    'title' => $request->title,
                    'start' => $request->start,
                    'end' => $request->end,
                ]);
                return response()->json($event);
                break;
            case 'update':
                $event = Event::find($request->id)->update([
                    'title' => $request->title,
                    'start' => $request->start,
                    'end' => $request->end,
                ]);
                return response()->json($event);
                break;
            case 'delete':
                $event = Event::find($request->id)->delete();
                return response()->json($event);
                break;
            default:
                # code...
                break;
        }
    }
}

Inside above code, we have two methods –

  • index() method for frontend layout of fullcalendar.

  • ajax() method responsible to process ajax request when insert, update and delete.

Create Template

Next, needs to create fullcalendar.blade.php file inside /resources/views folder.

Open fullcalendar.blade.php file and write this following code into it. This will give the frontend layout for fullcalendar.

fullcalendar.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 FullCalendar Ajax CRUD Tutorial Example</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" />
</head>
<body>
    <div class="container">
        <div class="jumbotron">
            <div class="container text-center">
                <h3>Laravel 10 FullCalendar Ajax CRUD Tutorial Example</h3>
            </div>
        </div>
        <div id='calendar'></div>
    </div>
    <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.24.0/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.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 = $('#calendar').fullCalendar({
                editable: true,
                events: SITEURL + "/fullcalendar",
                displayEventTime: false,
                editable: true,
                eventRender: function(event, element, view) {
                    if (event.allDay === 'true') {
                        event.allDay = true;
                    } else {
                        event.allDay = false;
                    }
                },
                selectable: true,
                selectHelper: true,
                select: function(start, end, allDay) {
                    var title = prompt('Event Title:');
                    if (title) {
                        var start = $.fullCalendar.formatDate(start, "Y-MM-DD");
                        var end = $.fullCalendar.formatDate(end, "Y-MM-DD");
                        $.ajax({
                            url: SITEURL + "/fullcalendar-ajax",
                            data: {
                                title: title,
                                start: start,
                                end: end,
                                type: 'add'
                            },
                            type: "POST",
                            success: function(data) {
                                displayMessage("Event Created Successfully");
                                calendar.fullCalendar('renderEvent', {
                                    id: data.id,
                                    title: title,
                                    start: start,
                                    end: end,
                                    allDay: allDay
                                }, true);
                                calendar.fullCalendar('unselect');
                            }
                        });
                    }
                },
                eventDrop: function(event, delta) {
                    var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD");
                    var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD");
                    $.ajax({
                        url: SITEURL + '/fullcalendar-ajax',
                        data: {
                            title: event.title,
                            start: start,
                            end: end,
                            id: event.id,
                            type: 'update'
                        },
                        type: "POST",
                        success: function(response) {
                            displayMessage("Event Updated Successfully");
                        }
                    });
                },
                eventClick: function(event) {
                    var deleteMsg = confirm("Do you really want to delete?");
                    if (deleteMsg) {
                        $.ajax({
                            type: "POST",
                            url: SITEURL + '/fullcalendar-ajax',
                            data: {
                                id: event.id,
                                type: 'delete'
                            },
                            success: function(response) {
                                calendar.fullCalendar('removeEvents', event.id);
                                displayMessage("Event Deleted Successfully");
                            }
                        });
                    }
                }
            });
        });
        function displayMessage(message) {
            toastr.success(message, 'Event');
        }
    </script>
</body>
</html>

Add Route

Open web.php file from /routes folder. Add these routes into it.

web.php

//...
use App\Http\Controllers\FullCalendarController;
//...
Route::get('fullcalendar', [FullCalendarController::class, 'index']);
Route::post('fullcalendar-ajax', [FullCalendarController::class, 'ajax']);
//...

Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve

URL: http://127.0.0.1:8000/fullcalendar

Frontend

Create Event

Click on any date, add and save your event.

Update Event

To update any event, Simple you can move (drag and drop) that event into any of your date. It will be automatically updated.

Delete Event

To delete, simple click on event and confirm via javascript alert box. It will delete automatically via ajax request.

In database events table, you will see the events as –

We hope this article helped you to learn about Laravel 10 FullCalendar Ajax CRUD Tutorial Example in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Last updated