article

Tuesday, April 19, 2022

Laravel 9 Fullcalandar Jquery Ajax Create and Delete Event

Laravel 9 Fullcalandar Jquery Ajax Create and Delete Event

Bootstrap 3
https://getbootstrap.com/docs/3.3/getting-started/

https://cdnjs.com/libraries/moment.js

The Most Popular JavaScript Calendar
https://fullcalendar.io/
https://cdnjs.com/libraries/fullcalendar/3.5.1

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory. 

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

Creating Controller

php artisan make:controller FullCalendarController
C:\xampp\htdocs\laravel9\blog>php artisan make:controller FullCalendarController
change it with the following codes:
//blog\app\Http\Controllers\FullCalendarController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Event; //add Event Model

class FullCalendarController extends Controller
{
    public function getEvent(){
        if(request()->ajax()){
            $start = (!empty($_GET["start"])) ? ($_GET["start"]) : ('');
            $end = (!empty($_GET["end"])) ? ($_GET["end"]) : ('');
            $events = Event::whereDate('start', '>=', $start)->whereDate('end',   '<=', $end)
                    ->get(['id','title','start', 'end']);
            return response()->json($events);
        }
        return view('fullcalendar');
        
    }
    public function createEvent(Request $request){
        $data = $request->except('_token');
        $events = Event::insert($data);
        return response()->json($events);
    }
   
    public function deleteEvent(Request $request){
        $event = Event::find($request->id);
        return $event->delete();
    }
}
Creating Model
php artisan make:model Event -m
C:\xampp\htdocs\laravel9\blog>php artisan make:model Event -m

This will create our model in the form of File.php file located : blog\app\Models\Event.php

we put -m when we create our model.
this will automatically make the migration for our model and you will see that in yourproject/database/migrations
blog\database\migrations\create_events_table.php
edit code blog\database\migrations\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->increments('id');
            $table->string('title');
            $table->dateTime('start');
            $table->dateTime('end');
            $table->timestamps();
        });
    }

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

php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table
//blog\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_date','end_date'];
}
Creating Routes
blog\routes\web.php
//blog\routes\web.php
<?php
use Illuminate\Support\Facades\Route;

//Route::get('/', function () {
//    return view('welcome');
//});
   
Route::get('/getevent', 'FullCalendarController@getEvent')->name('getevent');
Route::post('/createevent','FullCalendarController@createEvent')->name('createevent');
Route::post('/deleteevent','FullCalendarController@deleteEvent')->name('deleteevent');
Creating Views
blog\resources\views\fullcalendar.blade.php
//blog\resources\views\fullcalendar.blade.php
<!doctype html>
<html lang="en">
<head>
<title>Laravel 9 Fullcalandar Jquery Ajax Create and Delete Event </title>
  <link href='https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css' rel='stylesheet'>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.5.1/fullcalendar.min.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.5.1/fullcalendar.min.js"></script>
</head>
<body>
<div class="container"><p><h1>Laravel 9 Fullcalandar Jquery Ajax Create and Delete Event </h1></p>
    <div class="panel panel-primary">
        <div class="panel-heading">
               Laravel 9 Fullcalandar Jquery Ajax Create and Delete Event 
        </div>
        <div class="panel-body" >
            <div id='calendar'></div>
        </div>
    </div>
</div>
</body>
<script>
    $(document).ready(function () {
        var calendar = $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,basicWeek,basicDay'
            },
            navLinks: true,
            editable: true,
            events: "getevent",           
            displayEventTime: false,
            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 = moment(start, 'DD.MM.YYYY').format('YYYY-MM-DD'); 
                var end = moment(end, 'DD.MM.YYYY').format('YYYY-MM-DD'); 
                $.ajax({ 
                    url: "{{ URL::to('createevent') }}",
                    data: 'title=' + title + '&start=' + start + '&end=' + end +'&_token=' +"{{ csrf_token() }}",
                    type: "post",
                    success: function (data) {
                        alert("Added Successfully");
                        $('#calendar').fullCalendar('refetchEvents');
                    }
                });
            }
        },
        eventClick: function (event) {
            var deleteMsg = confirm("Do you really want to delete?");
            if (deleteMsg) { 
               $.ajax({
                    type: "POST",
                    url: "{{ URL::to('deleteevent') }}",
                    data: "&id=" + event.id+'&_token=' +"{{ csrf_token() }}",
                    success: function (response) {
                        if(parseInt(response) > 0) {
                            $('#calendar').fullCalendar('removeEvents', event.id);
                            alert("Deleted Successfully");
                        }
                    }
                });
            }
        }
        });
    });
</script>
</html>
Edit RouteServiceProvider.php
blog\app\Providers\RouteServiceProvider.php
uncomment protected $namespace = 'App\\Http\\Controllers';

Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Related Post