How To Create Calendar Event In Laravel 9 Using AJAX

WebSolutionStuff | Dec-28-2022 | Categories : Laravel PHP jQuery

In this article, we will see how to create a calendar event in laravel 9 using ajax. Here, we will learn how to add events in the full calendar in laravel using jquery ajax. In the calendar, we will perform crud operations in laravel 7, laravel 8, and laravel 9.

You can add the event, edit the event on the calendar and delete the event in the full calendar. Also, you can drag and drop the event from one date to another date.

So, let's see the laravel 9 full calendar example, how to add events in the full calendar in laravel 7/8/9, how to create an event in the calendar using jquery, and how to use fullcalendar in laravel 9.

Step 1: Install Laravel 9

Step 2: Create Model and Migration

Step 3: Create CalendarController

Step 4: Create Routes

Step 5: Create Blade File

Step 6: Run Laravel Application

 

Step 1: Install Laravel 9

In this step, we will install the laravel 9 application using the following command.

composer create-project laravel/laravel laravel9_fullcalendar_example

 

 

Step 2: Create Model and Migration

In this step, we will create migration using the following command.

php artisan make:migration create_events_table

Migration:

<?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');
            $table->date('start');
            $table->date('end');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('events');
    }
};

After that, we will migrate the table into the database using the following command.

php artisan migrate

Now, we will create the Event.php model. So, add the following code to that file.

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;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array

     */
    protected $fillable = [
        'title', 'start', 'end'
    ];
}
 
Step 3: Create CalendarController

Now, we will create CalendarController using the following command. So, add the following code to that file.

php artisan make:controller CalendarController

app/Http/Controllers/CalendarController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Event;
  
class CalendarController 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:
             info("Default");
             break;
        }
    }
}

 

 

Step 4: Create Routes

In this step, we will add routes in the web.php file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\CalendarController;
  
/*
|--------------------------------------------------------------------------
| 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::controller(CalendarController::class)->group(function(){
    Route::get('full-calendar', 'index');
    Route::post('full-calendar-ajax', 'ajax');
});

 

Step 5: Create Blade File

Now, we will create a fullcalendar.blade.php file. So, add the following code to that file. Also, we will add fullcalendar jquery and CSS CDN files.

resources/views/fullcalendar.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How To Create Calendar Event In Laravel 9 Using AJAX - Websolutionstuff</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <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">
    <h1>How To Create Calendar Event In Laravel 9 Using AJAX - Websolutionstuff</h1>
    <div id='calendar'></div>
</div>
  
<script type="text/javascript">
  
$(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 + "/full-calendar",
                    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 + "/full-calendar-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 + '/full-calendar-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 + '/full-calendar-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>

 

Step 6: Run Laravel Application

Now, run the laravel 9 fullcalendar crud operation using ajax.

php artisan serve

 


You might also like:



Recommended Post


Featured Post






Follow us
facebooklogo github instagram twitter