Laravel 8 Ajax CRUD With Yajra Datatable

Websolutionstuff | Jan-05-2022 | Categories : Laravel PHP jQuery MySQL Bootstrap

In this tutorial, we will see laravel 8 ajax crud with yajra datatable. I will show you how to create ajax crud operations in laravel 8. In laravel 8 ajax crud operation, we can perform without page refresh. You don't want to page reload when you insert, update, delete data then you should use ajax call in your laravel 8.

Also, we can use yajra datatable to perform an ajax crud operation in laravel 8 or crud operation in laravel 8 using ajax. you can also perform laravel 8 ajax crud with a modal popup. Follow the jquery data table ajax crud example tutorial step by step and get output.

So, let's start the crud operation in laravel 8 using ajax.

Step 1 : Create Laravel 8 Project

Step 2 : Setup Database

Step 3 : Add/Create Migration Table

Step 4 : Install yajra/laravel-datatables package.

Step 5 : Add Resource Route

Step 6 : Add Controller and Model

Step 7 : Add Blade Files

 

Step 1 : Create Laravel 8 Project

Type the following command in the terminal and create a fresh laravel 8 project.

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

 

 

Step 2 : Database Setup

In the second step, we will configure a database. for example database name, username, password, etc, So, open the .env file and add all details like as below.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database name(blog)
DB_USERNAME=database username(root)
DB_PASSWORD=database password(NULL)

 

Step 3 : Add/Create Migration Table

We are creating an ajax crud example for posts. So first, we have to create migration for the "posts" table using laravel php artisan command. So, the first type below command:

php artisan make:migration create_posts_table --create=posts

After running this command you will find a PHP file here location "database/migrations/" in this file you need to add the below code.

<?php 

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

class CreatePostsTable extends Migration { 

/** 
* Run the migrations. 
* 
* @return void */ 

public function up() 
{ 
    Schema::create('posts', function (Blueprint $table) { 
            $table->bigIncrements('id');
            $table->string('title')->nullable();
            $table->longText('description')->nullable();
            $table->timestamps();
        });
    }

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

after this, we need to run this migration by the following command in our terminal.

php artisan migrate

 

 

Step 4 : Install yajra/laravel-datatables package

Now, we need to install yajra/laravel-datatables in our project. So, just run below the following command in your terminal.

composer require yajra/laravel-datatables-oracle

After completing the step above, use the following command to publish configuration & assets:

php artisan vendor:publish --tag=datatables

 

Step 5 : Add Resource Route

Now, Add Resource route in Routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostAjaxController;

Route::resource('ajaxposts', PostAjaxController::class);

 

Step 6 : Add Controller and Model

create the PostAjaxController using the following command.

php artisan make:controller PostAjaxController --resource --model=Post

Now make changes in the model, you will find the model in this path app/Models/Post.php and add the below code in post.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Model;
   
class Post extends Model
{
    protected $fillable = [
        'id', 'title', 'description'
    ];
}

After changes in the model you will find PostAjaxController.php in this path app/Http/Controllers/PostAjaxController.php.

 

 

So, copy the below code and paste it to your controller.

<?php
         
namespace App\Http\Controllers;
          
use App\Models\Post;
use Illuminate\Http\Request;
use DataTables;
        
class PostAjaxController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
   
        if ($request->ajax()) {
            $post = Post::latest()->get();
            return Datatables::of($post)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){
   
                           $btn = '<a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-primary btn-sm editPost">Edit</a>';
   
                           $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-sm deletePost">Delete</a>';
    
                            return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
      
        return view('postAjax',compact('post'));
    }
     
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        Post::updateOrCreate(['id' => $request->id],
                ['title' => $request->title, 'description' => $request->description]);        
   
        return response()->json(['success'=>'Post saved successfully.']);
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Post
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $post = Post::find($id);
        return response()->json($post);
    }
  
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Post
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Post::find($id)->delete();
     
        return response()->json(['success'=>'Post deleted successfully.']);
    }
}

 

 

Step 7 : Add Blade Files

In this step, we will create a blade file for this example. So, create postAjax.blade.php in this path resources/views/postAjax.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 Ajax CRUD With Yajra Datatable - www.websolutionstuff.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
    <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
</head>
<body>
    
<div class="container">
    <h1>Laravel 8 Ajax CRUD With Yajra Datatable - www.websolutionstuff.com</h1>
    <a class="btn btn-info" href="javascript:void(0)" id="createNewPost"> Add New Post</a>
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Title</th>
                <th>Description</th>
                <th width="280px">Action</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
   
<div class="modal fade" id="ajaxModelexa" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modelHeading"></h4>
            </div>
            <div class="modal-body">
                <form id="postForm" name="postForm" class="form-horizontal">
                   <input type="hidden" name="id" id="id">
                    <div class="form-group">
                        <label for="title" 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 Name" value="" required>
                        </div>
                    </div>
     
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Description</label>
                        <div class="col-sm-12">
                            <textarea id="description" name="description" required placeholder="Enter Description" class="form-control"></textarea>
                        </div>
                    </div>
      
                    <div class="col-sm-offset-2 col-sm-10">
                     <button type="submit" class="btn btn-primary" id="savedata" value="create">Save Post
                     </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
    
</body>
    
<script type="text/javascript">
  $(function () {
     
      $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
    });
    
    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('ajaxposts.index') }}",
        columns: [
            {data: 'DT_RowIndex', name: 'DT_RowIndex'},
            {data: 'title', name: 'title'},
            {data: 'description', name: 'description'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });
     
    $('#createNewPost').click(function () {
        $('#savedata').val("create-post");
        $('#id').val('');
        $('#postForm').trigger("reset");
        $('#modelHeading').html("Create New Post");
        $('#ajaxModelexa').modal('show');
    });
    
    $('body').on('click', '.editPost', function () {
      var id = $(this).data('id');
      $.get("{{ route('ajaxposts.index') }}" +'/' + id +'/edit', function (data) {
          $('#modelHeading').html("Edit Post");
          $('#savedata').val("edit-user");
          $('#ajaxModelexa').modal('show');
          $('#id').val(data.id);
          $('#title').val(data.title);
          $('#description').val(data.description);
      })
   });
    
    $('#savedata').click(function (e) {
        e.preventDefault();
        $(this).html('Sending..');
    
        $.ajax({
          data: $('#postForm').serialize(),
          url: "{{ route('ajaxposts.store') }}",
          type: "POST",
          dataType: 'json',
          success: function (data) {
     
              $('#postForm').trigger("reset");
              $('#ajaxModelexa').modal('hide');
              table.draw();
         
          },
          error: function (data) {
              console.log('Error:', data);
              $('#savedata').html('Save Changes');
          }
      });
    });
    
    $('body').on('click', '.deletePost', function () {
     
        var id = $(this).data("id");
        confirm("Are You sure want to delete this Post!");
      
        $.ajax({
            type: "DELETE",
            url: "{{ route('ajaxposts.store') }}"+'/'+id,
            success: function (data) {
                table.draw();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });
     
  });
</script>
</html>

Copy the below command and run it in the terminal.

php artisan serve

 

 

Then open your web browser and add the following URL in the browser.

http://localhost:8000/ajaxposts

 


You might also like :

Recommended Post
Featured Post
How To Create Pagination Using jQuery
How To Create Pagination Using...

In this article, we will see how to create pagination using jquery. We will create jquery pagination using mul...

Read More

Nov-08-2022

How To Send Mail Using Gmail In Laravel 9
How To Send Mail Using Gmail I...

In this article, we will see how to send mail using gmail in laravel 9. we will learn laravel 9 to send mail u...

Read More

Aug-03-2022

Multi Step Form Wizard jQuery Validation
Multi Step Form Wizard jQuery...

In this article, we will see multi step form wizard jquery validation. Here, we will learn jquery validation for mu...

Read More

Jan-30-2023

Laravel 9 Generate PDF File Using DomPDF
Laravel 9 Generate PDF File Us...

In this tutorial, we will see laravel 9 generate pdf file using dompdf. For generating pdf files we will use the la...

Read More

Feb-25-2022