Thursday, 4 April 2019

Laravel 5.8 Ajax Crud Tutorial using DataTables

Part 1




Part 2




Part 3




Part 4




After Learning Simple CRUD (Create, Read, Update, Delete) operation in Laravel 5.8 with file upload, Now we have start learning advance level Crud Application in Laravel 5.8 by using Ajax with jQuery DataTables and Bootstrap Modal. So, user can perform all Crud operation on same without refresh of web page. Because here it will make single page Ajax Crud Application with File Upload in Laravel 5.8 by jQuery DataTables server side processing and form operation done by using Bootstrap modal.

For make Laravel 5.8 Crud Application using Ajax with DataTables and Bootstrap model. So first for use DataTables with Laravel 5.8, here we have will use Yajra DataTables package. By using Yajra Laravel DataTables plugin we can easily implement Server Side Processing of Data in Laravel 5.8 framework. So, User can list all records in tabular formate with different features like pagination of data, sorting of data and filter or search of data.

Same way for perform all Insert Update Delete data using Ajax in Laravel 5.8 framework. Here we will use Bootstrap modal. By using Bootstrap modal, we will make form in modal, because modal will pop up Insert data or edit data form on web page. So, user can perform all add edit delete data operation on single page in Laravel 5.8 using Ajax. Below you can step by step process of implementing Ajax Crud tutorial in Laravel 5.8 using Yajra DataTables package and Bootstrap modal.


Laravel 5.8 Ajax Crud Tutorial using DataTables



Step 1 - Install Laravel 5.8


First we want to Download Laravel 5.8 version for developing Crud application using Ajax. For this you have to open your terminal or command prompt and write below command. It will download Laravel 5.8 in your define directory.


composer create-project laravel/laravel=5.8 ajax-crud --prefer-dist


Step 2 - Laravel 5.8 Database Connection


Once Laravel 5.8 has been downloaded then after we have to make Database connection. For this first you have to open config/database.php and define Mysql Database configuration.



.......

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'testing'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]),
        ],

........


After this you have to open .env file and in that file also you have to define Mysql Database configuration, which you can find below.



.......

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

........


Step 3 - Create Table


For Create Crud Application, first we have to create Mysql table. For create Mysql table from Laravel 5.8 application we have to write following artisan command in your command prompt.


php artisan make:migration create_ajax_cruds_table --create=ajax_cruds


Above command will command create migration file in database/migrations folder. In that file we have to define table column which you want to define in Mysql table. Below you can find source code of migration file.


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAjaxCrudsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('ajax_cruds', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('image');
            $table->timestamps();
        });
    }

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


Lastly for create Mysql table in your Database, you have to write following command in your terminal or command prompt. It will create ajax_cruds table in your define Database.


php artisan migrate


Step 4 - Create Model in Laravel 5.8


Now we want to make Model in Laravel 5.8, For this you have to write following command in your terminal or command prompt. It will create model file here app/AjaxCrud.php.


php artisan make:model AjaxCrud -m


Under this app/AjaxCrud.php file, you have to define table column for database operation which source code you can find below.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class AjaxCrud extends Model
{
    protected $fillable = [
     'first_name', 'last_name', 'image'
    ];
}


Step 5 - Install Yajra DataTabbles Package in Laravel 5.8


For use jQuery DataTables plugin in Laravel 5.8, for this first we want to install Yajra DataTables plugin in Laravel 5.8 application. For this we have to write following command in your computer terminal or command prompt.


composer require yajra/laravel-datatables-oracle


Above command will download Yajra DataTables package in your Laravel 5.8 application. For use of Yajra DataTables package in Laravel 5.8 framework, we have to set this package providers and alias details.


.....
'providers' => [
 ....
 Yajra\Datatables\DatatablesServiceProvider::class,
]
'aliases' => [
 ....
 'Datatables' => Yajra\Datatables\Facades\Datatables::class,
]
.....


Lastly we want to publish this Yajra DataTables package, for this we have to write following command.


php artisan vendor:publish





Step 6 - Create Controller in Laravel 5.8


Controller mostly used for handle HTTP request. Create new controller in Laravel 5.8 framework, we have to write following command.


php artisan make:controller AjaxCrudController --resource


This command will create AjaxCrudController.php file in app/Http/Controllers folder. In this controller file you can find all in build required method for do Crud operation. Under this controller for use AjaxCrud model, first we have to define use App\AjaxCrud; this statement at the header of the AjaxCrudController.php file.

index() - This is the root method of this controller. This method will received Ajax request for load data in jQuery DataTables plugin. If this method received ajax request then it will load data in jQuery DataTables plugin. In this ajax block you can find yajra datatables package code.

store() - For Insert Data into Mysql table using ajax in Laravel 5.8, here we have use store() method of AjaxCrudController.php. This method will received Ajax request for insert or add data. Under this method first it has validate for data. If there is any validation fails then it will send response to ajax request in JSON format. But there is no any validation fails then it will continue execution of code and first it will upload profile image of user and then after it will insert data into mysql table. And lastly it will send json response to ajax request.

edit() - This method is used for fetch single row of data from mysql table, and send data to ajax request in json formate which will be display under Bootstrap modal form.

update() - This method has received ajax request for update existing mysql table data. In this method first it check user has select profile image or not. If User is select image then in this method it will validate form data with selected file is image or not. But Suppose user has not select image then it will only validate textbox data only. If there is any validation error occur then it will send data to ajax request in json formate. After successfully validate form data then it will update data.

destroy() - For delete or remove mysql data, ajax request will be send to destroy() method. It will delete or remove mysql data in Laravel 5.8 by using ajax.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\AjaxCrud;
use Validator;

class AjaxCrudController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if(request()->ajax())
        {
            return datatables()->of(AjaxCrud::latest()->get())
                    ->addColumn('action', function($data){
                        $button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Edit</button>';
                        $button .= '&nbsp;&nbsp;';
                        $button .= '<button type="button" name="delete" id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
                        return $button;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
        return view('ajax_index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $rules = array(
            'first_name'    =>  'required',
            'last_name'     =>  'required',
            'image'         =>  'required|image|max:2048'
        );

        $error = Validator::make($request->all(), $rules);

        if($error->fails())
        {
            return response()->json(['errors' => $error->errors()->all()]);
        }

        $image = $request->file('image');

        $new_name = rand() . '.' . $image->getClientOriginalExtension();

        $image->move(public_path('images'), $new_name);

        $form_data = array(
            'first_name'        =>  $request->first_name,
            'last_name'         =>  $request->last_name,
            'image'             =>  $new_name
        );

        AjaxCrud::create($form_data);

        return response()->json(['success' => 'Data Added successfully.']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if(request()->ajax())
        {
            $data = AjaxCrud::findOrFail($id);
            return response()->json(['data' => $data]);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $image_name = $request->hidden_image;
        $image = $request->file('image');
        if($image != '')
        {
            $rules = array(
                'first_name'    =>  'required',
                'last_name'     =>  'required',
                'image'         =>  'image|max:2048'
            );
            $error = Validator::make($request->all(), $rules);
            if($error->fails())
            {
                return response()->json(['errors' => $error->errors()->all()]);
            }

            $image_name = rand() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('images'), $image_name);
        }
        else
        {
            $rules = array(
                'first_name'    =>  'required',
                'last_name'     =>  'required'
            );

            $error = Validator::make($request->all(), $rules);

            if($error->fails())
            {
                return response()->json(['errors' => $error->errors()->all()]);
            }
        }

        $form_data = array(
            'first_name'       =>   $request->first_name,
            'last_name'        =>   $request->last_name,
            'image'            =>   $image_name
        );
        AjaxCrud::whereId($request->hidden_id)->update($form_data);

        return response()->json(['success' => 'Data is successfully updated']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $data = AjaxCrud::findOrFail($id);
        $data->delete();
    }
}


Step 7 - Create Blades Files


For display output data in browser, in Laravel 5.8 we have to create blade file in resources/views folder. Under this folder we have create ajax_index.blade.php file. In this file you can find HTML code and jQuery code for display data in jQuery Datatable.


<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - DataTables Server Side Processing using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 Ajax Crud Tutorial - Delete or Remove Data</h3>
     <br />
     <div align="right">
      <button type="button" name="create_record" id="create_record" class="btn btn-success btn-sm">Create Record</button>
     </div>
     <br />
   <div class="table-responsive">
    <table class="table table-bordered table-striped" id="user_table">
           <thead>
            <tr>
                <th width="10%">Image</th>
                <th width="35%">First Name</th>
                <th width="35%">Last Name</th>
                <th width="30%">Action</th>
            </tr>
           </thead>
       </table>
   </div>
   <br />
   <br />
  </div>
 </body>
</html>

<div id="formModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Add New Record</h4>
        </div>
        <div class="modal-body">
         <span id="form_result"></span>
         <form method="post" id="sample_form" class="form-horizontal" enctype="multipart/form-data">
          @csrf
          <div class="form-group">
            <label class="control-label col-md-4" >First Name : </label>
            <div class="col-md-8">
             <input type="text" name="first_name" id="first_name" class="form-control" />
            </div>
           </div>
           <div class="form-group">
            <label class="control-label col-md-4">Last Name : </label>
            <div class="col-md-8">
             <input type="text" name="last_name" id="last_name" class="form-control" />
            </div>
           </div>
           <div class="form-group">
            <label class="control-label col-md-4">Select Profile Image : </label>
            <div class="col-md-8">
             <input type="file" name="image" id="image" />
             <span id="store_image"></span>
            </div>
           </div>
           <br />
           <div class="form-group" align="center">
            <input type="hidden" name="action" id="action" />
            <input type="hidden" name="hidden_id" id="hidden_id" />
            <input type="submit" name="action_button" id="action_button" class="btn btn-warning" value="Add" />
           </div>
         </form>
        </div>
     </div>
    </div>
</div>

<div id="confirmModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h2 class="modal-title">Confirmation</h2>
            </div>
            <div class="modal-body">
                <h4 align="center" style="margin:0;">Are you sure you want to remove this data?</h4>
            </div>
            <div class="modal-footer">
             <button type="button" name="ok_button" id="ok_button" class="btn btn-danger">OK</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>


<script>
$(document).ready(function(){

 $('#user_table').DataTable({
  processing: true,
  serverSide: true,
  ajax:{
   url: "{{ route('ajax-crud.index') }}",
  },
  columns:[
   {
    data: 'image',
    name: 'image',
    render: function(data, type, full, meta){
     return "<img src={{ URL::to('/') }}/images/" + data + " width='70' class='img-thumbnail' />";
    },
    orderable: false
   },
   {
    data: 'first_name',
    name: 'first_name'
   },
   {
    data: 'last_name',
    name: 'last_name'
   },
   {
    data: 'action',
    name: 'action',
    orderable: false
   }
  ]
 });

 $('#create_record').click(function(){
  $('.modal-title').text("Add New Record");
     $('#action_button').val("Add");
     $('#action').val("Add");
     $('#formModal').modal('show');
 });

 $('#sample_form').on('submit', function(event){
  event.preventDefault();
  if($('#action').val() == 'Add')
  {
   $.ajax({
    url:"{{ route('ajax-crud.store') }}",
    method:"POST",
    data: new FormData(this),
    contentType: false,
    cache:false,
    processData: false,
    dataType:"json",
    success:function(data)
    {
     var html = '';
     if(data.errors)
     {
      html = '<div class="alert alert-danger">';
      for(var count = 0; count < data.errors.length; count++)
      {
       html += '<p>' + data.errors[count] + '</p>';
      }
      html += '</div>';
     }
     if(data.success)
     {
      html = '<div class="alert alert-success">' + data.success + '</div>';
      $('#sample_form')[0].reset();
      $('#user_table').DataTable().ajax.reload();
     }
     $('#form_result').html(html);
    }
   })
  }

  if($('#action').val() == "Edit")
  {
   $.ajax({
    url:"{{ route('ajax-crud.update') }}",
    method:"POST",
    data:new FormData(this),
    contentType: false,
    cache: false,
    processData: false,
    dataType:"json",
    success:function(data)
    {
     var html = '';
     if(data.errors)
     {
      html = '<div class="alert alert-danger">';
      for(var count = 0; count < data.errors.length; count++)
      {
       html += '<p>' + data.errors[count] + '</p>';
      }
      html += '</div>';
     }
     if(data.success)
     {
      html = '<div class="alert alert-success">' + data.success + '</div>';
      $('#sample_form')[0].reset();
      $('#store_image').html('');
      $('#user_table').DataTable().ajax.reload();
     }
     $('#form_result').html(html);
    }
   });
  }
 });

 $(document).on('click', '.edit', function(){
  var id = $(this).attr('id');
  $('#form_result').html('');
  $.ajax({
   url:"/ajax-crud/"+id+"/edit",
   dataType:"json",
   success:function(html){
    $('#first_name').val(html.data.first_name);
    $('#last_name').val(html.data.last_name);
    $('#store_image').html("<img src={{ URL::to('/') }}/images/" + html.data.image + " width='70' class='img-thumbnail' />");
    $('#store_image').append("<input type='hidden' name='hidden_image' value='"+html.data.image+"' />");
    $('#hidden_id').val(html.data.id);
    $('.modal-title').text("Edit New Record");
    $('#action_button').val("Edit");
    $('#action').val("Edit");
    $('#formModal').modal('show');
   }
  })
 });

 var user_id;

 $(document).on('click', '.delete', function(){
  user_id = $(this).attr('id');
  $('#confirmModal').modal('show');
 });

 $('#ok_button').click(function(){
  $.ajax({
   url:"ajax-crud/destroy/"+user_id,
   beforeSend:function(){
    $('#ok_button').text('Deleting...');
   },
   success:function(data)
   {
    setTimeout(function(){
     $('#confirmModal').modal('hide');
     $('#user_table').DataTable().ajax.reload();
    }, 2000);
   }
  })
 });

});
</script>


Step 8 - Set Resource Route


Lastly, We need to set resource route for ajax crud application. For this we have to open routes/web.php file.


Route::resource('ajax-crud', 'AjaxCrudController');

Route::post('ajax-crud/update', 'AjaxCrudController@update')->name('ajax-crud.update');

Route::get('ajax-crud/destroy/{id}', 'AjaxCrudController@destroy');


For run Laravel 5.8 application, you can write following command.


php artisan serve


For see Laravel 5.8 application in your browser, you have to write following url.


http://localhost:8000/ajax-crud

39 comments:

  1. If can add the vuejs, hope can see more vue js, thks.

    ReplyDelete
  2. why not you making a demo of compare products. pls make it

    ReplyDelete
  3. DataTables warning: table id=user_table - Ajax error. For more information about this error, please see http://datatables.net/tn/7

    ReplyDelete
  4. It good, hope have vue js with laravel,

    ReplyDelete
  5. excelent !!!
    Thanks for sharing your knowledge

    ReplyDelete
  6. Ребят, удалите строчку - php artisan make:migration create_ajax_cruds_table --create=ajax_cruds, т. к. php artisan make:model AjaxCrud -m создает еще одну идентичную миграцию для модели AjaxCrud.

    ReplyDelete
  7. It show ajax error when i have more than 5 columns in my table

    ReplyDelete
  8. Hello Weblesson teacher.
    I'm have a problem with the edit method. I'm copied it method exactly but edit button don't show nothing. Can You help me please?

    ReplyDelete
    Replies
    1. i have equal this problem, you can help me?

      Delete
  9. When I click edit button to edit an entity, it doesn't work.

    ReplyDelete
  10. some errors "token mis matched error"

    ReplyDelete
  11. works like charm :)

    thank you very much!!!

    ReplyDelete
  12. Hi,,

    Create Record button : Can't create the record,


    -------------***---------------
    Error

    Request URL: http://127.0.0.1:8000/ajax-crud
    Request Method: POST
    Status Code: 302 Found
    Remote Address: 127.0.0.1:8000

    -------------***---------------
    How to solve, Help me

    ReplyDelete
  13. Very Greate Work Sir,But It is better if you put a whole folder of project then we just migrate the database table

    ReplyDelete
  14. Thank You so much sir... This is a much more helpfull tutorial

    ReplyDelete
  15. return datatables()->of(AjaxCrud::latest()->get())

    I get an error like ::latest() does not exist

    ReplyDelete
  16. can i use this in blade extends from masterr??

    ReplyDelete
  17. hi weblesson,
    my delete button is not working, what's the problem ?

    ReplyDelete
  18. Thanks sir this is very helpful for me

    ReplyDelete
  19. thank you i was trying more than 15 times at diffrent source but this was the only post that actually work and helped me.

    ReplyDelete
  20. DataTables warning: table id=user_table - Ajax error. For more information about this error, please see http://datatables.net/tn/7

    this error showing???

    ReplyDelete
  21. DataTables warning: table id=material_table - Ajax error. For more information about this error, please see http://datatables.net/tn/7

    ReplyDelete
  22. hi!! i cant insert image, you can help me please

    ReplyDelete
  23. I am using mongDB with lumens. I think it's cx similar to laravel and mySQL

    ReplyDelete
  24. Sensational! I had some problems with my integration, but I managed to solve it and it works perfectly.

    ReplyDelete