Laravel
876
w3alert.com
14-11-2020
Laravel 8 ajax crud with modal tutorial. In this example, i will show you how to implement ajax todo crud app in laravel 8 app using datatable js with modal. And you will learn how to create a Laravel Bootstrap Model Todo CRUD web application using dataTables and Ajax .
Note that, It is very easy to build first a Bootstrap Model CRUD application in Laravel with MySQL database and DataTables. And along with that, you will learn how to perform Laravel CRUD operation with form data on client side validation (using jQuery validation libaries).
And here you will learn how to open and reset the larva modal popup. How to insert data using Ajax's larvae with datatables, how to get data using Ajax and display the data on the bootstrap model popup and edit the form modal and data in mysql database table using Ajax in laravel web application.
First Step, you need to download or install laravel web application new setup on your local machine. you can use the following command to download or install laravel application new setup:
composer create-project laravel/laravel laravel-datatables-crud –-prefer-dist
If you want to install a specific version of laravel, you can follow the following tutorial
https://w3alert.com/laravel-tutorial/laravel-install-on-windows-ubuntu-with-composer
After that, you will set up the database credentials in .env file. So open your .env file and update database credentials following:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=database_name DB_USERNAME=root DB_PASSWORD=root
Next, we need to create a model and migration in your laravel web application using the php artisan make:model model_name -m. So run the following command in your project root directory.
Go to the command prompt
cd/project_root_directory
php artisan make:model Todo -m
after that, go to database/migrations/ and find created migration file and add fields, as you want to in your database table.
Your migration file looks like:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTodosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('todos', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('email'); $table->text('message'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('todos'); } }
And go to the app/ directory and find the model file. And add table field name as fillable property:- protected $fillable = ['title', 'description'];
Your model file looks like:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Todo extends Model { use HasFactory; protected $fillable = ['title', 'description']; }
Next, go to command prompt and run the following command:
php artisan migrate OR php artisan migrate:fresh
This php artisan migrate command creates a table in your database.
Next, you need to install yajra dataTables laravel package in your web applications. So go to your command prompt and run the following command to install the latest laravel yajra dataTables package:
composer require yajra/laravel-datatables-oracle
When the package of yajra datatables is installed. After that this package will have to be registered in the Laravel web application of the app. For this, you can register this package of instruction follow below.
App_root_directory/config/app.php
'providers' => [ Yajra\Datatables\DatatablesServiceProvider::class, ], 'aliases' => [ 'Datatables' => Yajra\Datatables\Facades\Datatables::class, ]
When you will register the package of yajra dataTables. After this the package will have to be published with the command given below.
php artisan vendor:publish
Next step, go to routes/web.php file and update the following routes into your file:
use App\Http\Controllers\DataTableTodoCrudController; Route::get('list', [DataTableTodoCrudController::class, 'index']); Route::get('add-todo', [DataTableTodoCrudController::class, 'create']); Route::post('post-todo', [DataTableTodoCrudController::class, 'store']); Route::get('edit-todo/{id?}', [DataTableTodoCrudController::class, 'edit']); Route::post('update-todo', [DataTableTodoCrudController::class, 'update']); Route::get('delete-todo/{id?}', [DataTableTodoCrudController::class, 'delete']);
Now, you need to generate or create a controller file using php artisan command, so use the php artisan make:controller command and generate/create a new controller file:
php artisan make:controller DataTableTodoCrudController
We will create a method in this controller file. This method will also show the list and handle the Ajax request.
After that, go to App/Http/Controllers/ directory and find the created DataTableTodoCrudController file and update the following code into your file:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator,Redirect,Response; Use App\Todo; class DataTableTodoCrudController extends Controller { /* Display todo list */ public function index() { if(request()->ajax()) { return datatables()->of(Todo::select([ 'id','title' , 'description', 'created_at' ])) ->addIndexColumn() ->addColumn('action', function($data){ $editUrl = url('edit-todo/'.$data->id); $btn = '<a href="'.$editUrl.'" data-toggle="tooltip" data-original-title="Edit" class="edit btn btn-primary btn-sm">Edit</a>'; $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$data->id.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteTodo">Delete</a>'; return $btn; }) ->rawColumns(['action']) ->make(true); } return view('list-todo'); } /* Display todo add form */ public function create() { return view('add-todo'); } /* insert todo list into mysql database*/ public function store(Request $request) { $data = request()->validate([ 'title' => 'required', 'description' => 'required', ]); $check = Todo::create($data); return Redirect::to("list")->withSuccess('Great! Todo has been inserted'); } /* display edit todo form with data */ public function edit(Request $request, $id) { $data['todo'] = Todo::where('id', $id)->first(); if(!$data['todo']){ return redirect('/list'); } return view('edit-todo', $data); } /* update todo into mysql database */ public function update(Request $request) { $data = request()->validate([ 'title' => 'required', 'description' => 'required', ]); if(!$request->id){ return redirect('/list'); } $check = todo::where('id', $request->id)->update($data); return Redirect::to("list")->withSuccess('Great! Todo has been updated'); } /* delete todo from mysql database */ public function delete(Request $request, $id) { $check = Todo::where('id', $id)->delete(); return Response::json($check); } }
Next, you need to create some blade views file, so go resource/views directory and create the blade views file.
Go to resource/views/ then create new blade view file and update the following code into your files:
Create list-todo.blade.php file and Update following code into your file:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>Laravel Insert Todo Example Tutorial- w3alert.com</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" /> </head> <body> <div class="container mt-5"> <form id="add-todo" method="post" action="{{ url('post-todo') }}"> @csrf <div class="form-group"> <label for="formGroupExampleInput">Title</label> <input type="text" name="title" class="form-control" id="formGroupExampleInput" placeholder="Please enter title"> <span class="text-danger">{{ $errors->first('title') }}</span> </div> <div class="form-group"> <label for="message">Description</label> <textarea class="form-control" name="description" placeholder="Please enter description"></textarea> <span class="text-danger">{{ $errors->first('description') }}</span> </div> <div class="form-group"> <button type="submit" class="btn btn-success" id="btn-send">Submit</button> </div> </form> </div> </body> </html>
Update following code into your the edit-todo.blade.php file:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>Laravel Update Todo Example Tutorial- w3alert.com</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" /> </head> <body> <div class="container mt-5"> <form id="add-todo" method="post" action="{{ url('update-todo') }}"> @csrf <input type="hidden" name="id" class="form-control" value="{{ $todo->id }}" id="formGroupExampleInput"> <div class="form-group"> <label for="formGroupExampleInput">Title</label> <input type="text" name="title" class="form-control" id="formGroupExampleInput" placeholder="Please enter title" value="{{ $todo->title }}"> <span class="text-danger">{{ $errors->first('title') }}</span> </div> <div class="form-group"> <label for="message">Description</label> <textarea name="description" class="form-control" id="description" placeholder="Please enter description">{{ $todo->description }}</textarea> <span class="text-danger">{{ $errors->first('description') }}</span> </div> <div class="form-group"> <button type="submit" class="btn btn-success" id="btn-send">Submit</button> </div> </form> </div> </body> </html>
Update following code into your the list-todo.blade.php file:
<!DOCTYPE html> <html lang="en"> <head> <title>Laravel DataTables Todo CRUD Example Tutorial - w3alert.com</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"> <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> </head> <body> <div class="container mt-4"> <h2 class="text-center mt-2 mb-3 alert alert-success">Laravel DataTables Todo CRUD Example Tutorial</h2> <a href="{{ url('add-todo') }}" class="text-center btn btn-success mb-1">Create Todo</a> <table class="table table-bordered" id="laravel-datatable-crud"> <thead> <tr> <th>Id</th> <th>Title</th> <th>Description</th> <th>Created at</th> <th>Action</th> </tr> </thead> </table> </div> <script> $(document).ready( function () { $('#laravel-datatable-crud').DataTable({ processing: true, serverSide: true, ajax: { url: "{{ url('list') }}", type: 'GET', }, columns: [ { data: 'id', name: 'id' }, { data: 'title', name: 'title' }, { data: 'description', name: 'description' }, { data: 'created_at', name: 'created_at' }, { data: 'action', name: 'action' } ] }); }); $('body').on('click', '.deleteTodo', function () { var todo_id = $(this).data("id"); if(confirm("Are You sure want to delete !")) { $.ajax({ type: "get", url: "{{ url('delete-todo') }}"+'/'+todo_id, success: function (data) { var oTable = $('#laravel-datatable-crud').dataTable(); oTable.fnDraw(false); }, error: function (data) { console.log('Error:', data); } }); } }); </script> </body> </html>
In the given list-todo.blade.php file, we have created a bootstrap model.
When clicking on add todo button this Laravel DataTables Ajax todo CRUD with model in your web application, then this bootstrap model will open. And you can add todo in this model.
Next things, when you click on the edit button in this application, the same model will open. But this time your todo information will be seen in this model.
In the same blade view, we have created some JavaScript functions that will open the model of bootstrap to add todo to apps, update todo, and delete todo. And these functions will also call the ajax to insert and update and delete data in the MySQL database.
You can use the following command artisan command to start the development server:
php artisan serve
The final step, go to your browser and type the below-given URL into your browser:
http://localhost:8000/list OR http://localhost/laravel-datatables-crud/public/list
You can also download laravel dataTables crud web application with validation here Download
The yajra dataTables Web Application Looks Like: