Laravel 7.x FullCalendar Ajax Example Tutorial

Laravel 7.x FullCalendar Ajax Example Tutorial

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.

Laravel Fullcalendar Tutorial

Just follow the below steps and integrate full calendar in you laravel application:

  • 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 6 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

It command will create one model name Event and also create one migration file for the Events table. After successfully run the command go to database/migrations file and put the below here :

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

We will 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:

//fullcalender
Route::get('fullcalendar','FullCalendarController@index');
Route::post('fullcalendar/create','FullCalendarController@create');
Route::post('fullcalendar/update','FullCalendarController@update');
Route::post('fullcalendar/delete','FullCalendarController@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\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('fullcalender');
    }
   
  
    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://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js" integrity="sha256-4iQZ6BVL4qNKlQ27TExEhBN1HFPvAvAMbFavKKosSWQ=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.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 + '&amp;start=' + start + '&amp;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 + '&amp;start=' + start + '&amp;end=' + end + '&amp;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: "&amp;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/fullcalendar

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 full calendar in laravel application. Here you have learned how you can show, add, update, and delete events on fullcalendar.

Recommended Laravel Tutorial

  1. Laravel 7 Tutorial From Scratch | Step By Step
  2. DataTables In Laravel 7 – Example Tutorial
  3. Laravel 7 CRUD Example Tutorial (Step By Step)
  4. Laravel 7 Ajax CRUD(DataTables Js) Tutorial Example
  5. Laravel 7 – Ajax CRUD (Operation) Application Example
  6. Laravel 7 Angular JS CRUD Example Tutorial

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

AuthorTuts Make

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Javascript, JQuery, Laravel, Codeigniter, Vue JS, Angular JS, React Js, WordPress and Bootstrap from a starting stage.

2 replies to Laravel 7.x FullCalendar Ajax Example Tutorial

  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

Leave a Reply

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