laravel 9

Laravel 9 FullCalendar Tutorial

Pinterest LinkedIn Tumblr

In this tutorial,I will show to you, how you can integrate a full-calendar in laravel 9application. I have written step by step instruction of laravel 9 FullCalendar ajax.

In this example, I will implement add an event, update event and delete event on the full-calendar using ajax.

Step 1 – Install laravel 9 App
Step 2 – Connecting App to Database
Step 3 – Create Migration And Model
Step 4: Create Model

Step 5: Create Events Table Seeder Step 6: Create Controller File
Step 6 : Create Routes
Step 7: Create Blade File
Step 8 – Run Development Server

Step 1: Create the application

 

We need to run command to create Laravel 9 projects.

 

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

Step 2 – Connecting App to Database

Next step, we will set the database credentials in the application. Let’s open your project .env file and set the database credentials here.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Laravel8CrudImage
DB_USERNAME=root
DB_PASSWORD=root@123

Step 3: Create Migration and Model

php artisan make:migration create_events_table

Now open file and put below code.

Path: database/migrations/

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

Run Migration Command


php artisan migrate

Step 4: Create Model

app/Models/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'
    ];
}

Step 5: Create Events Table Seeder

Now,I will put some dummy data in events table. so, we will insert dummy data created by seeder. run following command create seed file.


php artisan make:seeder AddDummyEvent

After run this command open database/seeds/AddDummyEvent.php file and put following code in it.

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Event;

class AddDummyEvent extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
   public function run()
    {
        $data = [
        	['title'=>'Demo Event-1', 'start'=>'2021-07-11', 'end'=>'2021-07-12'],
        	['title'=>'Demo Event-2', 'start'=>'2021-07-11', 'end'=>'2021-07-13'],
        	['title'=>'Demo Event-3', 'start'=>'2021-07-14', 'end'=>'2021-07-14'],
        	['title'=>'Demo Event-3', 'start'=>'2021-07-17', 'end'=>'2021-07-17'],
        ];
        foreach ($data as $key => $value) {
        	Event::create($value);
        }
    }
}

Step 6: Create Controller File

php artisan make:controller FullCalenderController

After running this command you can check FullCalenderController.php file in your folder app/Http/Controllers directory and open FullCalenderController.php file and put bellow code in that file.

app/Http/Controllers/FullCalenderController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Event;
  
class FullCalenderController 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('fullcalender');
    }
 
    /**
     * 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;
        }
    }
}

Step 7: Create Routes

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\FullCalenderController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('fullcalender', [FullCalenderController::class, 'index']);
Route::post('fullcalenderAjax', [FullCalenderController::class, 'ajax']);

Step 8: Create Blade File

Here I will create fullcalender.blade.php file for display fullcalender and I will write js code create, read, delete, update. now create fullcalender.blade.php file and put bellow code:

touch resources/views/fullcalender.blade.php

<!DOCTYPE html>
<html>
   <head>
      <title>Laravel 9 FullCalendar Tutorial</title>
      <meta name="csrf-token" content="{{ csrf_token() }}">
      <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"></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>
      <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">
               <h1>Laravel 9 FullCalendar Tutorial</h1>
            </div>
         </div>
         <div id='calendar'></div>
      </div>
      <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 + "/fullcalender",
                             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 + "/fullcalenderAjax",
                                         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 + '/fullcalenderAjax',
                                     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 + '/fullcalenderAjax',
                                         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>

Now, run below command

php artisan server

http://127.0.0.1:8000/fullcalender

Git : https://github.com/siddharth018/Laravel-8-FullCalendar

Write A Comment