Laravel
310
Sumit Suryavanshi
14-11-2020
Laravel 8 first datatables crud tutorial. In this example, i will show you how to create first datatable crud in laravel 8 app. And as well as, you will learn step by step how to create CRUD (create, read, update, delete operation) web application in laravel 8 app with DataTables js
This tutorial will guide you from scratch to create CRUD using DataTables in laravel 8 app. It is very easy to build first a CRUD application in Laravel with MySQL database and DataTables. And along with that, you will learn how to perform Laravel CRUD operation with server-side validation.
To CRUD means to create, read, update, delete operations with data from MySQL database tables.
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::post('store', [DataTableTodoCrudController::class, 'store']); Route::get('edit/{id?}', [DataTableTodoCrudController::class, 'edit']); Route::get('delete/{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\Models\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){ $btn = '<a href="javascript:void(0)" data-toggle="tooltip" data-original-title="Edit" class="edit btn btn-primary btn-sm" onclick=editTodo("'.$data->id.'")>Edit</a>'; $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip" data-original-title="Delete" class="btn btn-danger btn-sm " onclick=editTodo("'.$data->id.'")>Delete</a>'; return $btn; }) ->rawColumns(['action']) ->make(true); } return view('list-todo'); } /* insert and update todo into mysql database*/ public function store(Request $request) { $data = request()->validate([ 'title' => 'required', 'description' => 'required', ]); if($request->todo_id != '') { $check = Todo::where('id', $request->todo_id)->update($data); }else{ $check = Todo::create($data); } return Response::json($check); } /* display edit todo form with data */ public function edit(Request $request, $id) { $data['todo'] = Todo::where('id', $id)->first(); return Response::json($data['todo']); } /* 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 following blade view files and update the following code into your files:
Update following code into your the add-todo.blade.php file:
<!DOCTYPE html> <html lang="en"> <head> <title>Laravel 8 DataTables Todo CRUD Example Tutorial - w3alert.com</title> <meta name="csrf-token" content="{{ csrf_token() }}"> <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> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> </head> <body> <div class="container mt-4"> <h2 class="text-center mt-2 mb-3 alert alert-success">Laravel Ajax Todo CRUD with DataTables Example Tutorial</h2> <a href="javascript:void(0)" class="text-center btn btn-success mb-1" onclick="addTodo()">Create Todo</a> <table class="table table-bordered" id="laravel-datatable-ajax-crud"> <thead> <tr> <th>Id</th> <th>Title</th> <th>Description</th> <th>Created at</th> <th>Action</th> </tr> </thead> </table> </div> <div class="modal fade" id="todo-modal" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="todo-modal"></h4> </div> <div class="modal-body"> <form id="todoForm" name="todoForm" class="form-horizontal"> <input type="hidden" name="todo_id" id="todo_id"> <div class="form-group"> <label for="name" class="col-sm-2 control-label">Title</label> <div class="col-sm-12"> <input type="text" class="form-control" id="title" name="title" placeholder="Enter Tilte" value="" maxlength="50" required=""> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Description</label> <div class="col-sm-12"> <input type="text" class="form-control" id="description" name="description" placeholder="Enter Description" value="" required=""> </div> </div> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary" id="btn-save" value="create">Save changes </button> </div> </form> </div> <div class="modal-footer"> </div> </div> </div> </div> <script> $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $(document).ready( function () { $('#laravel-datatable-ajax-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' } ] }); }); //for add todo function addTodo() { $('#todo-modal').find("input,textarea").val('').end(); $('#todo-modal').modal('show'); } // for edit todo function editTodo(id) { $('#todo-modal').find("input,textarea").val('').end(); $.get('edit'+'/'+id, function (data) { $('#todo-modal').modal('show'); $('#todo_id').val(data.id); $('#title').val(data.title); $('#description').val(data.description); }) } //for delete todo function deleteTodo(id) { if(confirm("Are You really want to delete this todo!")){ $.ajax({ type: "get", url: "{{ url('delete') }}"+'/'+id, success: function (data) { var oTable = $('#laravel-datatable-ajax-crud').dataTable(); oTable.fnDraw(false); }, error: function (data) { console.log('Error:', data); } }); } } if ($("#todoForm").length > 0) { $("#todoForm").validate({ submitHandler: function(form) { var actionType = $('#btn-save').val(); $('#btn-save').html('Sending..'); $.ajax({ data: $('#todoForm').serialize(), url: "{{ url('store') }}", type: "POST", dataType: 'json', success: function (data) { $('#todoForm').trigger("reset"); $('#todo-modal').modal('hide'); $('#btn-save').html('Save Changes'); var oTable = $('#laravel-datatable-ajax-crud').dataTable(); oTable.fnDraw(false); }, error: function (data) { console.log('Error:', data); $('#btn-save').html('Save Changes'); } }); } }) } </script> </body> </html>
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
The yajra dataTables Web Application Looks Like: