LARAVEL Tutorial


Laravel 7 DataTable Todo CRUD Example Tutorial

Author:- w3alert.com
Updated Date:-11-08-2020

In this tutorial, you will learn how to create CRUD (create, read, update, delete operation) web application in laravel with DataTables js. And also we will provide a downloading link, where you can download this laravel dataTables crud web application.

In this tutorial, we will create a Laravel CRUD DataTables web application. 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.

Laravel DataTables CRUD Example Tutorial

  • Install Laravel Application
  • Configure Database Detail
  • Create Todo Model and Migration
  • Run Migration
  • Install and Register Yajra DataTable
  • Create Routes
  • Generate Controller By Artisan
  • Create Blade View
  • Start Development Server

Install Laravel 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

Configure Database Detail

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

Create Todo Model and Migration

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;

use Illuminate\Database\Eloquent\Model;

class Todo extends Model
{
    protected $fillable = ['title', 'description']; 
}

Run Migration

Before you will run php artisan migrate command. Go to app/providers/AppServiceProvider.php and update the below code :

..
use Illuminate\Support\Facades\Schema;
 
....
function boot()
{
    Schema::defaultStringLength(191);
}
... 

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.

Install and Register Yajra Datatable

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

Create Routes

Next step, go to routes/web.php file and update the following routes into your file:

//display todo list
Route::get('list','[email protected]');

//insert and update todo into database
Route::post('store','[email protected]');

//display edit todo model
Route::get('edit/{id?}','[email protected]');

//delete todo from mysql database
Route::get('delete/{id?}','[email protected]');

Generate Controller By Artisan

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){
                   
                   $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);
    }

}

Create Blade Views

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:

  • add-todo.blade.php
  • edit-todo.blade.php
  • list-todo.blade.php

Update following code into your the add-todo.blade.php file:

<!DOCTYPE html>
 
<html lang="en">
<head>

<title>Laravel 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>

Start development server

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:

Add todo in Mysql Database

Update todo in Mysql Database

Reference

This tutorial idea has taken from this https://www.tutsmake.com/laravel-7-6-datatable-ajax-crud-with-modal/