Wednesday 16 October 2019

Laravel 6 Crud Application using Yajra Datatables and Ajax

Part 1 - How to Implement Yajra Datatables in Laravel 6




Part 2 - How to Insert data into Mysql in Laravel 6 using Ajax with Bootstrap Modal




Part 3 - How to Edit or Update Mysql Data in Laravel 6 using Ajax




Part 4 - How to Delete or Remove Data From Mysql in Laravel 6 using Ajax




Are you looking for web tutorial on Laravel 6 framework, then you have come on the right place, because in this post, you can learn how to make Single page Crud application in Laravel 6 framework by using Yajra Datatables package and Ajax. This framework version has been release in the month of September 2019. This framework has required your PHP version must be greater than 7.2. There are following changes has done in Laravel 6 framework.

  1. String & Array Helpers Moved To Package
  2. Carbon 2.0 Supported
  3. Added cursor method in Eloquent
  4. Update on Eloquent BelongsTo::update Method
  5. Declaration Of Primary Key Type

For learn any framework version, first you need to have learn some basic operation like CRUD (Create, Read, Update, Delete). So, you can understand, how can we perform database insert, update, delete, select data operation. This is our first post on Laravel 6 framework.

So, here we have make Single Page Crud Application in which we have use Yajra Datatables package with Ajax. So, here you can also learn how to use Yajra Datatables package with Laravel 6 framework. Here also we have use Ajax, so you can perform all operation like Add, Edit and Remove data operation on same page like Desktop application. That means by using Ajax using make web application working like Desktop application, this is because all operation will be done on client side, and only database related request has been send to server. So, Database related operation will be done without refresh of web page. Below you can find step by step process for how to use Ajax and Yajra Datatables package in Laravel 6 for make Crud Application with Mysql database.

  1. Create Table in Database
  2. Download and Install Laravel 6 framework
  3. Download & Install Yajra Datatables package
  4. Create Model Class
  5. Create Controller in Laravel 6
  6. Create Blade File in Laravel 6
  7. Set Route in Laravel 6
  8. Run Laravel 6 Application






Create Table in Database


Run following sql script in your database. It will make sample_datas table in your define database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `sample_datas`
--

CREATE TABLE `sample_datas` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `first_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `last_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `sample_datas`
--

INSERT INTO `sample_datas` (`id`, `first_name`, `last_name`, `created_at`, `updated_at`) VALUES
(1, 'John', 'Smith', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(2, 'Peter', 'Parker', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(3, 'Larry', 'Degraw', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(4, 'Tabitha', 'Russell', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(5, 'Susan', 'Diener', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(6, 'William', 'Batiste', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(7, 'Bessie', 'Tucker', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(8, 'Eva', 'King', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(9, 'Dorothy', 'Hays', '2019-10-14 03:30:00', '2019-10-14 03:30:00'),
(10, 'Nannie', 'Ayers', '2019-10-14 03:30:00', '2019-10-14 03:30:00'),
(11, 'Gerald', 'Brown', '2019-10-14 04:30:00', '2019-10-14 04:30:00'),
(12, 'Judith', 'Smith', '2019-10-14 04:30:00', '2019-10-14 04:30:00'),
(13, 'Betty', 'McLaughlin', '2019-10-14 13:30:00', '2019-10-14 13:30:00'),
(14, 'Delores', 'Schumacher', '2019-10-14 13:30:00', '2019-10-14 13:30:00'),
(15, 'Gloria', 'Romero', '2019-10-14 06:30:00', '2019-10-14 06:30:00'),
(16, 'Bobbie', 'Wilson', '2019-10-14 06:30:00', '2019-10-14 06:30:00'),
(17, 'Paul', 'Pate', '2019-10-14 13:30:00', '2019-10-14 13:30:00'),
(18, 'Ryan', 'Hoang', '2019-10-14 13:30:00', '2019-10-14 13:30:00');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `sample_datas`
--
ALTER TABLE `sample_datas`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_datas`
--
ALTER TABLE `sample_datas`
  MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;


Download and Install Laravel 6 framework


First we need to download Laravel 6 framework, so for download we have use composer, because this framework dependncy has been manage by composer. For this we have go to command prompt and then after go to directory in which we want to download Laravel 6 framework. After this we have to run composer command and then after we have to learn following command.


composer create-project --prefer-dist laravel/laravel laravel-6


This command will make laravel-6 folder in define directory and in that it will download Laravel 6 framework. So this way we can download Laravel 6 framework.

Download & Install Yajra Datatables package


Here we have use Yajra Datatables package with Laravel 6 framework. So for this we have to download and install Yajra Datatables package. For this we have to go command prompt and run following command.


composer require yajra/laravel-datatables-oracle


This command will download the Yajra Datatables compatible version with Laravel 6 framework. Now we want to publish it. For this we have to open config/app.php file and in this file we have to define service providers details and class aliases details which you can find below.


<?php

--------

'providers' => [

---------

Yajra\DataTables\DataTablesServiceProvider::class,

---------

],

'aliases' => [

---------

'DataTables' => Yajra\DataTables\Facades\DataTables::class,

---------

],

--------

?>


Create Model Class


In Laravel 6 framework, here we have use Model class for make crud application. For this we have go to command and run follwing command.


php artisan make:model Sample_data --migration


This command will make Model class file in app folder with name like Sample_data.php. In this file we have to define table column name for database related operation which you can find below.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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


Create Controller in Laravel 6


In Laravel 6 controller has been used for handle http request of application. In Laravel 6 controller class has been store in app/Http/Controllers folder. Here want to create Crud controller, that means in this controller class all crud operation method inbuild made at the time of creating class. For create controller file in Laravel 6, we have to go command prompt and write following command.


php artisan make:controller SampleController --resource --model=Sample_data


Above command will make SampleController.php file in app/Http/Controllers folder. In this controller class first we want to import Datatables class. For this we have to write use DataTables; this statement, it will import Yajra Datatables package class in this controller class.

In this class following crud method has been inbuild made at the time of creation of class.

index(Request $request) - This is the root method of this class, this method has been used for displaying data from database. In this method we have check first any ajax request has been received or not. If any ajax request has been received, then it will used Sample_data.php modal class for fetch latest data from Mysql database and then after it has use Yajra Datatables package for load data in jQuery Datatables plugin. On without ajax request it has load sample_data.blade.php view file in browser.
store(Request $request) - This store() method has been received ajax request for add or insert data into Mysql table. In this method first it has validate form data by using Validator class. If any validation error has occur then it has send error response to Ajax request. But suppose there is no any validation has found in form data then it has proceed for insert new record in Mysql table by using Model class and after successfully inserting of data into database then it has send success response to ajax request.

edit($id) - This method has received Ajax get request for fetch particular user data from Database. Once this method has received data from mysql table, then it send response with data of particular user in JSON format.

update(Request $request, Sample_data $sample_data) - This is another method which has been used for update or edit mysql data in Laravel 6 framework. This method has been used for edit or update particular user data based on value of primary key.

destroy($id) - This method has been used for remove resource from database storage. This method will received Ajax request for delete data from Mysql table in Laravel 6 framework.

app/Http/Controllers/SampleController

<?php

namespace App\Http\Controllers;

use App\Sample_data;
use Illuminate\Http\Request;
use DataTables;
use Validator;

class SampleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if($request->ajax())
        {
            $data = Sample_data::latest()->get();
            return DataTables::of($data)
                    ->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;&nbsp;<button type="button" name="edit" id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
                        return $button;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
        return view('sample_data');
    }

    /**
     * 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'
        );

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

        Sample_data::create($form_data);

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

    }

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

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Sample_data  $sample_data
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Sample_data $sample_data)
    {
        $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
        );

        Sample_data::whereId($request->hidden_id)->update($form_data);

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

    }

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



Create Blade File in Laravel 6


In Laravel 6 framework blade file has been store in resources/views folder. Generally in Laravel 6 blade file has been used to display HTML output in browser. Here we have create sample_data.blade.php blade file for this single page crud application. In this file, we have already imported required library for use jQuery Datatables plugin, jquery and Bootstrap.

In this file, first we have create one HTML table defination with three table column with id is equal to user_table. Based on this id value, we will initialize jQuery Datatable plugin, which you can find in jquery code below.
Here we have use Bootstrap modal for form. Because here we want to make single page application, so by using Bootstrap modal we can add new data by using modal form.

For submit form data, here we have use Ajax request. When we have submit form data then at that time Ajax request has been send to store() method of SampleController.php file.
resources/views/sample_data.blade.php


<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>How to Delete or Remove Data From Mysql in Laravel 6 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">How to Delete or Remove Data From Mysql in Laravel 6 using Ajax</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 id="user_table" class="table table-bordered table-striped">
     <thead>
      <tr>
       <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">
          @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>
                <br />
                <div class="form-group" align="center">
                 <input type="hidden" name="action" id="action" value="Add" />
                 <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('sample.index') }}",
  },
  columns: [
   {
    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');
  $('#form_result').html('');

  $('#formModal').modal('show');
 });

 $('#sample_form').on('submit', function(event){
  event.preventDefault();
  var action_url = '';

  if($('#action').val() == 'Add')
  {
   action_url = "{{ route('sample.store') }}";
  }

  if($('#action').val() == 'Edit')
  {
   action_url = "{{ route('sample.update') }}";
  }

  $.ajax({
   url: action_url,
   method:"POST",
   data:$(this).serialize(),
   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);
   }
  });
 });

 $(document).on('click', '.edit', function(){
  var id = $(this).attr('id');
  $('#form_result').html('');
  $.ajax({
   url :"/sample/"+id+"/edit",
   dataType:"json",
   success:function(data)
   {
    $('#first_name').val(data.result.first_name);
    $('#last_name').val(data.result.last_name);
    $('#hidden_id').val(id);
    $('.modal-title').text('Edit 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:"sample/destroy/"+user_id,
   beforeSend:function(){
    $('#ok_button').text('Deleting...');
   },
   success:function(data)
   {
    setTimeout(function(){
     $('#confirmModal').modal('hide');
     $('#user_table').DataTable().ajax.reload();
     alert('Data Deleted');
    }, 2000);
   }
  })
 });

});
</script>




Set Route in Laravel 6


In this step we have to set the route for all SampleController.php file. For this we have to open routes/web.php file. And this file we have set route for all method of SampleController.php file.

routes/web.php

<?php

Route::resource('sample', 'SampleController');

Route::post('sample/update', 'SampleController@update')->name('sample.update');

Route::get('sample/destroy/{id}', 'SampleController@destroy');

?>


Above code will set the route of all method of SampleController.php class.

Run Laravel 6 Application


So, here our all code is ready, now we want to run Laravel 6 application. For this we have to go command prompt and write following command.


php artisan serve


This command will start laravel application, and it will return base url of your Laravel 6 application. For run above code you have to write following url in your browser.


http://127.0.0.1:8000/sample

By above url, you can check your first crud application which has been make in Laravel 6 framework, by using Yajra Datatables package and Ajax. Remaining source code will be updated very soon.






8 comments:

  1. The action [edit] button does not work. Action [delete] and [create record] does work and I can't figure out how to fix it :(

    ReplyDelete
    Replies
    1. $(document).on('click', '.edit', function(){

         //omission\(^o^)/

      url :"/sample/"+id+"/edit",

      //↓rewriting

      url :"sample/"+id+"/edit"

      Try it once. I hope this is helpful to you.



      Delete
  2. Hello, Thank you for your great tutorial. I love your work. I have a 404 error when I click on edit button. Not Found

    The requested URL /sample/16/edit was not found on this server.

    That's the only problem I met.

    Any idea please ?

    Thank you again.

    ReplyDelete
  3. hello thanks for this great tutorial,
    i have a question :
    how can i include CSRF TOKEN security using ajax ?
    Thanks in advance .

    ReplyDelete
  4. i think you forget something on route , action when edit button press it should be take action on route, please check your route. no action for edited

    ReplyDelete
  5. Hello,
    Thank you for this great tutorial you are the best.

    Please if you have time to show us how to implement yajra Buttons Plugin in our project.

    ReplyDelete
  6. i follow you step by step and dosen't work for me

    ReplyDelete
  7. how upload video and display into the blade file using yajara

    ReplyDelete