FullCalendar Ajax In Laravel 10

FullCalendar Ajax In Laravel 10

Laravel fullCalendar using ajax example tutorial. This tutorial demonstrates to you, how you can integrate a fullCalendar in your laravel application.

Here, you will learn step by step how you can easily use a fullcalendar with its events. In this example, We will implement add an event, update event and delete event on the fullcalendar using ajax.

FullCalendar Ajax In Laravel 10

Just follow the below steps and integrate fullCalendar in you laravel application with ajax:

  • Install Laravel App
  • Setup Database
  • Generate Migration & Model
  • Make Route
  • Create Controller & Methods
  • Create Blade View
  • Run Development Server

1). Install Laravel App

First, we need to download the laravel fresh setup. Use the below command and download fresh new laravel setup :

composer create-project --prefer-dist laravel/laravel blog

2). Setup Database

After successfully install laravel Application, Go to your project .env file and set up database credential and move next step :

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

3). Generate Migration & Model

Now we will create a table name event and it’s migration file. use the below command :

php artisan make:model Event -m

This command will create one model name Event and also create one migration file for the Events table.

After successfully run the command, Navigate to database/migrations folder and open create_events_table.php file. Then update the following code into create_users_table.php file, as follow:

<?php

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

class CreateEventsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->dateTime('start');
            $table->dateTime('end');
            $table->timestamps();
        });
    }

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

Next, migrate the table using the below command :

php artisan migrate

4). Make Route

In this step, Create two routes in the web.php file. Go to app/routes/web.php file and create two routes so update your routes in web.php file:

use App\Http\Controllers\FullCalendarController;


Route::get('fullcalendars', [FullCalendarController::class, 'index']);
Route::post('fullcalendar/create', [FullCalendarController::class, 'create']);
Route::post('fullcalendar/update', [FullCalendarController::class, 'update']);
Route::post('fullcalendar/delete', [FullCalendarController::class, 'destroy']);

5). Create Controller

We need to create a controller name FullCalendarController. Use the below command and create Controller :

php artisan make:controller FullCalendarController

After successfully create controller go to app/controllers/FullCalendarController.php and update the below code :

The first method is index(), it will show you fullcalendar.

The second method is create(), it will store your events into the database.

The third method is update(), it will update your fullcalendar event into database.

The final method is destroy(), it will delete your events into the database and fullcalendar.

<?php
  
namespace App\Http\Controllers;
  
use App\Models\Event;
use Illuminate\Http\Request;
use Redirect,Response;
  
class FullCalenderController extends Controller
{

    public function index()
    {
        if(request()->ajax()) 
        {

         $start = (!empty($_GET["start"])) ? ($_GET["start"]) : ('');
         $end = (!empty($_GET["end"])) ? ($_GET["end"]) : ('');

         $data = Event::whereDate('start', '>=', $start)->whereDate('end',   '<=', $end)->get(['id','title','start', 'end']);
         return Response::json($data);
        }
        return view('fullcalendar');
    }
   
  
    public function create(Request $request)
    {  
        $insertArr = [ 'title' => $request->title,
                       'start' => $request->start,
                       'end' => $request->end
                    ];
        $event = Event::insert($insertArr);   
        return Response::json($event);
    }
    

    public function update(Request $request)
    {   
        $where = array('id' => $request->id);
        $updateArr = ['title' => $request->title,'start' => $request->start, 'end' => $request->end];
        $event  = Event::where($where)->update($updateArr);

        return Response::json($event);
    } 


    public function destroy(Request $request)
    {
        $event = Event::where('id',$request->id)->delete();
  
        return Response::json($event);
    }    


}

6). Create Blade view

In this step, you need to create blade view file. Go to app/resources/views and create one file name fullcalendar.blade.php:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Fullcalender Add/Update/Delete Event Example Tutorial - Tutsmake.com</title>
  <meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/fullcalendar.min.css" />

<script src="https://cdn.jsdelivr.net/npm/[email protected]/moment.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/fullcalendar.min.js"></script>
<body>

  <div class="container">
      <div class="response"></div>
      <div id='calendar'></div>  
  </div>


</body>
</html>
Put the script on fullcalendar.blade.php, after the closing of the body tag
<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: true,
            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 HH:mm:ss");
                    var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");

                    $.ajax({
                        url: SITEURL + "fullcalendar/create",
                        data: 'title=' + title + '&start=' + start + '&end=' + end,
                        type: "POST",
                        success: function (data) {
                            displayMessage("Added Successfully");
                        }
                    });
                    calendar.fullCalendar('renderEvent',
                            {
                                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 HH:mm:ss");
                        var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
                        $.ajax({
                            url: SITEURL + 'fullcalendar/update',
                            data: 'title=' + event.title + '&start=' + start + '&end=' + end + '&id=' + event.id,
                            type: "POST",
                            success: function (response) {
                                displayMessage("Updated Successfully");
                            }
                        });
                    },
            eventClick: function (event) {
                var deleteMsg = confirm("Do you really want to delete?");
                if (deleteMsg) {
                    $.ajax({
                        type: "POST",
                        url: SITEURL + 'fullcalendar/delete',
                        data: "&id=" + event.id,
                        success: function (response) {
                            if(parseInt(response) > 0) {
                                $('#calendar').fullCalendar('removeEvents', event.id);
                                displayMessage("Deleted Successfully");
                            }
                        }
                    });
                }
            }

        });
  });

  function displayMessage(message) {
    $(".response").html("<div class='success'>"+message+"</div>");
    setInterval(function() { $(".success").fadeOut(); }, 1000);
  }
</script>

7). Run Development Server

You need to run the development server. Use the php artisan serve command and start your server :

 php artisan serve
If you want to run the project diffrent port so use this below command
php artisan serve --port=8080

Now we are ready to run our example so run bellow command to quick run.

http://localhost:8000/fullcalendars

If you want to remove public or public/index.php from URL In laravel, Click Me

Conclusion

In this tutorial, We have successfully integrated the fullCalendar into laravel application. Here you have learned how you can show, add, update, and delete events on fullcalendar.

Recommended Laravel Tutorial

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

3 replies to FullCalendar Ajax In Laravel 10

  1. To insert information in two tables at a time, how should I do it? For example: event and client tables

  2. Laravel full calendar ajax works successfully.

    Thank you

  3. Hello, thank you for this tutorial. It’s work fine. Please add more tutorials about laravel and fullcalendar

Leave a Reply

Your email address will not be published. Required fields are marked *