Laravel 9 AJAX CRUD Example

Websolutionstuff | Feb-11-2022 | Categories : Laravel PHP jQuery MySQL

In this post, we will learn how to create ajax crud operations in laravel 9. here, we will perform laravel 9 ajax crud example without page refresh. In his post we will use different CDN of bootstrap for designing purposes and also we will use data table CDN for ajax crud example in laravel 9.

So,let's see laravel 9 crud example with ajax and learn how to create ajax crud operations in laravel 9.

 

Step 1: Install Laravel 9 For Laravel 9 AJAX CRUD Example

Step 2: New Database Setup

Step 3: Create New Migration Table

Step 4: Create Resource Route

Step 5: Add Controller and Model

Step 6: Add Blade Files

 

Step 1: Install Laravel 9 For Laravel 9 AJAX CRUD Example

Here, we will Install laravel 9 for AJAX CRUDexample in laravel 9,type below command in your terminal

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

 

 

Step 2: New Database Setup

In this step, we will configure a database for laravel 9 ajax crud example.here, we need to set database name, username, password etc for our AJAX crud example of laravel 9. So open .env file and fill 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: Create New Migration Table

We are creating  AJAX crud for post example. So, create migration for "posts" table using laravel php artisan command.

php artisan make:migration create_posts_table --create=posts

After that, you will find php file in this location "database/migrations" in this file you need to copy 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: Create Resource Route

Now Add Resource route in Routes/web.php

use App\Http\Controllers\PostAjaxController;
Route::resource('ajaxposts', PostAjaxController::class);

 

Step 5: Add Controller and Model

Create the PostAjaxController and Post Model using the following command.

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

Now make changes in Model, you will find a model in this file location App/Post.php add below code in post.php

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

Now, we need to changes in PostAjaxController.php in this path app/Http/Controllers/PostAjaxController.php:

<?php
         
namespace App\Http\Controllers;
          
use App\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($data)
                    ->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.']);
    }
}

Now make changes in model in this folder App/Post.php add below code in post.php

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

 

 

Step 6: Add Blade Files

Create postAjax.blade.php in this path resources/views/postAjax.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 AJAX CRUD Example - 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 9 AJAX CRUD Example - 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>

 

Now, run the below command in your terminal to get output.

php artisan serve

 


You might also like :

Recommended Post
Featured Post
Github And Git Commands
Github And Git Commands

GitHub, Inc. is a United States-based global company that provides hosting for software development and version control...

Read More

Jul-15-2020

How To Add Summernote Editor In Laravel
How To Add Summernote Editor I...

In this tutorial, I will let you know how to use summernote editor in laravel, In laravel or PHP many editors are a...

Read More

Jun-17-2020

Laravel 9 Form Collective Example
Laravel 9 Form Collective Exam...

In this article, we will see laravel 9 form collective example. Here, we will learn how to use collective form and...

Read More

Jan-20-2023

How To Change Month Name In jQuery Datepicker
How To Change Month Name In jQ...

In this article, we will see how to change the month name in jquery datepicker. In the date picker, we can change t...

Read More

Jul-01-2022