Laravel 10 AJAX CRUD Operations Example

    In this article, we will see the laravel 10 ajax crud operations example. Here, we will learn about ajax crud operation in laravel 10. So, you can perform crud operation without page refresh using ajax call.

    In his article, we will use different CDN of bootstrap for designing purposes and also we will use datatable CDN for ajax crud example in laravel 10.

    So, let's see the ajax crud operation in laravel 10, laravel 10 ajax crud operation, how to create ajax crud operation in laravel 10, and crud operation using ajax in laravel 10.

    Step 1: Install Laravel 10 for AJAX CRUD Example

    Step 2: Setup Database Configure

    Step 3: Create New Migration Table

    Step 4: Create Resource Route

    Step 5: Add Controller and Model

    Step 6: Add Blade Files

    Step 7: Run Laravel 10 Application

Step 1: Install Laravel 10 for AJAX CRUD Example

    Here, we will Install laravel 10 for the AJAX CRUD example. So, type the below command in your terminal.

composer create-project --prefer-dist laravel/laravel blog
Read Also: Laravel 10 CRUD Operation Step By Step
Step 2: New Database Setup

    In this step, we will configure a database for the laravel 10 ajax crud example. Here, we need to set the database name, username, password, etc. So open the .env file and fill in all details like as below: 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_10_ajax_crud_example
DB_USERNAME=root
DB_PASSWORD=root
Step 3: Create New Migration Table

    We are creating  AJAX crud for the post examples. So, create migration for the "posts" table using the 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
Read Also: How To Create Calendar Event In Laravel 9 Using AJAX
Step 4: Create Resource Route

    Now, Add the resource route in the web.php file.

    routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\AjaxPostController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group that
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::resource('posts', AjaxPostController::class);
Step 5: Add Controller and Model

    In this step, we will create the AjaxPostController and Post Model using the following command.

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

    Now make changes in Post Model. So, add the below code in post.php.

    App/Models/Post.php

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

    Now, we need to changes in the AjaxPostController.php file. 

    app/Http/Controllers/AjaxPostController.php:

<?php
         
namespace App\Http\Controllers;
          
use App\Models\Post;
use Illuminate\Http\Request;
use DataTables;
        
class AjaxPostController 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('ajaxPost',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.']);
    }
}
Read More: Laravel 9 Ajax File Upload With Progress Bar
Step 6: Add Blade Files

    In this step, we will create an ajaxPost.blade.php file. 

    resources/views/ajaxPost.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 AJAX CRUD Operations Example - Websolutionstuff</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 10 AJAX CRUD Operations Example - Websolutionstuff</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 the output.

php artisan serve

    You might also like :

Bình luận
Vui lòng đăng nhập để bình luận
Một số bài viết liên quan