Friday, November 1, 2024
Google search engine
HomeLanguagesLaravel 8 Ajax CRUD with Yajra Datatable

Laravel 8 Ajax CRUD with Yajra Datatable

Laravel 8 Ajax CRUD using Datatables example; In this tutorial, you will learn from scratch how to create an ajax crud application using dataTable js, bootstrap modal, and jQuery inl aravel 8.

This laravel 8 ajax crud tutorial using datatables will create single page companies ajax crud application (SPA) using dataTables js, modal and jQuery in laravel 8. Where you can insert data without page reload using ajax jquery with bootstrap modal in laravel 8 apps.

And you will learn how to make a simple laravel 8 Ajax CRUD app using Datatable js, jQuery, and modal in laravel 8. also, how to insert,edit and delete data using ajax in laravel 8 with DataTables.

This ajax crud with bootstrap datatable and modal laravel 8 app will looks like following images:

  • List Of Companies – Laravel 8 ajax crud Datatables
  • Add Company – Laravel 8 ajax crud Datatables
  • Edit/Update Company – Laravel 8 ajax crud Datatables
  • Delete Company – Laravel 8 ajax crud Datatables

Laravel 8 Ajax CRUD Tutorial with Bootstrap 4 Modal and Pagination Example

Use the following steps to create an ajax crud application using dataTable js, bootstrap modal, and jQuery inl aravel 8:

  • Step 1 – Download Laravel 8 App
  • Step 2 – Database Configuration
  • Step 3 – Installing Yajra Datatables
  • Step 4 – Make Model & Migration
  • Step 5 – Make Routes
  • Step 6 – Create AJAX CRUD Datatables Controller
  • Step 7 – Create Blade Views File
    • companies.blade.php
    • company-action.blade.php
  • Step 8 – Run Development Server

Step 1 – Download Laravel 8 App

First of all, download or install laravel 8 new setup. So, open the terminal and type the following command to install the new laravel 8 app into your machine:

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

Step 2 – Database Configuration

Setup database with your downloaded/installed laravel 8 app. So, you need to find .env file and setup database details as following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password

Step 3 – Installing Yajra Datatables

Navigate to your downloaded laravel 8 app directory. And then install Yajra Datatables Packages in your laravel 8 by using the following command:

composer require yajra/laravel-datatables-oracle

Then configure datatables package. So go to config directory and open app.php file. And add the following service providers into app.php file:

config/app.php

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

 'aliases' => [

  'Datatables' => Yajra\Datatables\Facades\Datatables::class,
] 

Then publish laravel datatables vendor package by using the following command:

php artisan vendor:publish

Step 4 – Make Model & Migration

Open again your command prompt. And run the following command on it. To create model and migration file:

php artisan make:model Company -m

After that, open create_companies_table.php file inside /database/migrations/ directory. And the update the function up() with following code:

    public function up()
    {
        Schema::create('companies', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('address');
            $table->timestamps();
        });
    }

Then, open again command prompt and run the following command to create tables into database:

php artisan migrate

After that, visit app/models directory and open company.php model file. Then add the following code into it:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    use HasFactory;

    protected $fillable = [ 'name', 'email', 'address' ];
}

Step 5 – Make Routes

Then create routes for laravel crud app. So, open web.php file from the routes directory of laravel CRUD app. And update the following routes into the web.php file:

use App\Http\Controllers\DataTableAjaxCRUDController;

Route::get('ajax-crud-datatable', [DataTableAjaxCRUDController::class, 'index']);
Route::post('store-company', [DataTableAjaxCRUDController::class, 'store']);
Route::post('edit-company', [DataTableAjaxCRUDController::class, 'edit']);
Route::post('delete-company', [DataTableAjaxCRUDController::class, 'destroy']);

Step 6 – Create AJAX CRUD Datatables Controller

Create a controller by using the following command on the command prompt to create a controller file:

php artisan make:controller DataTableAjaxCRUDController

After that, visit at app/Http/controllers and open DataTableAjaxCRUDController.php file. And update the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Company;

use Datatables;

class DataTableAjaxCRUDController extends Controller
{
	/**
	 * Display a listing of the resource.
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function index()
	{
	    if(request()->ajax()) {
	        return datatables()->of(Company::select('*'))
	        ->addColumn('action', 'company-action')
	        ->rawColumns(['action'])
	        ->addIndexColumn()
	        ->make(true);
	    }
	    return view('companies');
	}
	 
	 
	/**
	 * Store a newly created resource in storage.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @return \Illuminate\Http\Response
	 */
	public function store(Request $request)
	{  

	    $companyId = $request->id;

	    $company   =   Company::updateOrCreate(
	    	        [
	    	         'id' => $companyId
	    	        ],
	                [
	                'name' => $request->name, 
	                'email' => $request->email,
	                'address' => $request->address
	                ]);    
	                    
	    return Response()->json($company);

	}
	 
	 
	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  \App\company  $company
	 * @return \Illuminate\Http\Response
	 */
	public function edit(Request $request)
	{   
	    $where = array('id' => $request->id);
	    $company  = Company::where($where)->first();
	 
	    return Response()->json($company);
	}
	 
	 
	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  \App\company  $company
	 * @return \Illuminate\Http\Response
	 */
	public function destroy(Request $request)
	{
	    $company = Company::where('id',$request->id)->delete();
	 
	    return Response()->json($company);
	}
}

Step 6 – Create Blade Views File

Create two blade views file, which is following:

  • companies.blade.php
  • company-action.blade.php

Go to resources/views directory. And create companies.blade.php and company-action.blade.php. And update the following code into the following this files:

companies.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Laravel 8 AJAX CRUD using DataTable js Tutorial From Scratch - Tutsmake.com</title>
    
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

    <link  href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">

    <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>

</head>
<body>

<div class="container mt-2">

<div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 8 Ajax CRUD DataTables Tutorial</h2>
            </div>
            <div class="pull-right mb-2">
                <a class="btn btn-success" onClick="add()" href="javascript:void(0)"> Create Company</a>
            </div>
        </div>
    </div>
   
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif

    <div class="card-body">

        <table class="table table-bordered" id="ajax-crud-datatable">
           <thead>
              <tr>
                 <th>Id</th>
                 <th>Name</th>
                 <th>Email</th>
                 <th>Address</th>
                 <th>Created at</th>
                 <th>Action</th>
              </tr>
           </thead>
        </table>

    </div>
   
</div>

  <!-- boostrap company model -->
    <div class="modal fade" id="company-modal" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title" id="CompanyModal"></h4>
          </div>
          <div class="modal-body">
            <form action="javascript:void(0)" id="CompanyForm" name="CompanyForm" class="form-horizontal" method="POST" enctype="multipart/form-data">
              <input type="hidden" name="id" id="id">
              <div class="form-group">
                <label for="name" class="col-sm-2 control-label">Company Name</label>
                <div class="col-sm-12">
                  <input type="text" class="form-control" id="name" name="name" placeholder="Enter Company Name" maxlength="50" required="">
                </div>
              </div>  

              <div class="form-group">
                <label for="name" class="col-sm-2 control-label">Company Email</label>
                <div class="col-sm-12">
                  <input type="email" class="form-control" id="email" name="email" placeholder="Enter Company Email" maxlength="50" required="">
                </div>
              </div>

              <div class="form-group">
                <label class="col-sm-2 control-label">Company Address</label>
                <div class="col-sm-12">
                  <input type="text" class="form-control" id="address" name="address" placeholder="Enter Company Address" required="">
                </div>
              </div>

              <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-primary" id="btn-save">Save changes
                </button>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            
          </div>
        </div>
      </div>
    </div>
<!-- end bootstrap model -->

</body>
<script type="text/javascript">
     
 $(document).ready( function () {

  $.ajaxSetup({
    headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
  });
    $('#ajax-crud-datatable').DataTable({
           processing: true,
           serverSide: true,
           ajax: "{{ url('ajax-crud-datatable') }}",
           columns: [
                    { data: 'id', name: 'id' },
                    { data: 'name', name: 'name' },
                    { data: 'email', name: 'email' },
                    { data: 'address', name: 'address' },
                    { data: 'created_at', name: 'created_at' },
                    {data: 'action', name: 'action', orderable: false},
                 ],
                 order: [[0, 'desc']]
       });

  });
  
  function add(){

       $('#CompanyForm').trigger("reset");
       $('#CompanyModal').html("Add Company");
       $('#company-modal').modal('show');
       $('#id').val('');

  }   
  function editFunc(id){
    
    $.ajax({
        type:"POST",
        url: "{{ url('edit-company') }}",
        data: { id: id },
        dataType: 'json',
        success: function(res){
          $('#CompanyModal').html("Edit Company");
          $('#company-modal').modal('show');
          $('#id').val(res.id);
          $('#name').val(res.name);
          $('#address').val(res.address);
          $('#email').val(res.email);
       }
    });
  }  

  function deleteFunc(id){
        if (confirm("Delete Record?") == true) {
        var id = id;
         
          // ajax
          $.ajax({
              type:"POST",
              url: "{{ url('delete-company') }}",
              data: { id: id },
              dataType: 'json',
              success: function(res){

                var oTable = $('#ajax-crud-datatable').dataTable();
                oTable.fnDraw(false);
             }
          });
       }
  }

  $('#CompanyForm').submit(function(e) {

     e.preventDefault();
  
     var formData = new FormData(this);
  
     $.ajax({
        type:'POST',
        url: "{{ url('store-company')}}",
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        success: (data) => {
          $("#company-modal").modal('hide');
          var oTable = $('#ajax-crud-datatable').dataTable();
          oTable.fnDraw(false);
          $("#btn-save").html('Submit');
          $("#btn-save"). attr("disabled", false);
        },
        error: function(data){
           console.log(data);
         }
       });
   });

</script>
</html>

Explaination of above given jQuery, ajax and javascript code:

On the companies.blade.php, we have created 5 jQuery, ajax, and javascript custom and built-in yajra datatables functions, which are the followings:

  • add()

The add() function will contain the given code and it’s show company add modal:

  function add(){

       $('#CompanyForm').trigger("reset");
       $('#CompanyModal').html("Add Company");
       $('#company-modal').modal('show');
       $('#id').val('');

  }  

  • editFunc()

The editFunc() function will contain the given code and it’s show company edit modal with company details:

  function editFunc(id){
    
    $.ajax({
        type:"POST",
        url: "{{ url('edit-company') }}",
        data: { id: id },
        dataType: 'json',
        success: function(res){
          $('#CompanyModal').html("Edit Company");
          $('#company-modal').modal('show');
          $('#id').val(res.id);
          $('#name').val(res.name);
          $('#address').val(res.address);
          $('#email').val(res.email);
       }
    });
  } 

  • deleteFunc()

The add() function will contain below given code and it’s delete company from database and yajra datatables:

  function deleteFunc(id){
        if (confirm("Delete Record?") == true) {
        var id = id;
         
          // ajax
          $.ajax({
              type:"POST",
              url: "{{ url('delete-company') }}",
              data: { id: id },
              dataType: 'json',
              success: function(res){

                var oTable = $('#ajax-crud-datatable').dataTable();
                oTable.fnDraw(false);
             }
          });
       }
  }

  • DataTable()

The DataTable() function will contain below given code and it’s render list of companies with pagination, search, sorting functionality:

    $('#ajax-crud-datatable').DataTable({
           processing: true,
           serverSide: true,
           ajax: "{{ url('ajax-crud-datatable') }}",
           columns: [
                    { data: 'id', name: 'id' },
                    { data: 'name', name: 'name' },
                    { data: 'email', name: 'email' },
                    { data: 'address', name: 'address' },
                    { data: 'created_at', name: 'created_at' },
                    {data: 'action', name: 'action', orderable: false},
                 ],
                 order: [[0, 'desc']]
    });

  • jQuery submit()

This submit function will send data to controller file using ajax for insert or update form data into database:

  $('#CompanyForm').submit(function(e) {

     e.preventDefault();
  
     var formData = new FormData(this);
  
     $.ajax({
        type:'POST',
        url: "{{ url('store-company')}}",
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        success: (data) => {
          $("#company-modal").modal('hide');
          var oTable = $('#ajax-crud-datatable').dataTable();
          oTable.fnDraw(false);
          $("#btn-save").html('Submit');
          $("#btn-save"). attr("disabled", false);
        },
        error: function(data){
           console.log(data);
         }
       });
   });

company-action.blade.php

<a href="javascript:void(0)" data-toggle="tooltip" onClick="editFunc({{ $id }})" data-original-title="Edit" class="edit btn btn-success edit">
	Edit
</a>
<a href="javascript:void(0);" id="delete-compnay" onClick="deleteFunc({{ $id }})" data-toggle="tooltip" data-original-title="Delete" class="delete btn btn-danger">
	Delete
</a>

Don’t forget to add the following yajra Datatables, jquery, and bootstrap library on companies.blade.php file:

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

    <link  href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">

    <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>

Step 8 – Run Development Server

Last step, open command prompt and run the following command to start developement server:

php artisan serve

Then open your browser and hit the following url on it:

http://127.0.0.1:8000/ajax-crud-datatable

Recommended Laravel Posts

RELATED ARTICLES

Most Popular

Recent Comments