Create Ajax CRUD Laravel 9 Application Example

Hello, Developers! Today we are going to learn how to Create Ajax CRUD Laravel 9 Application Example. This tutorial will walk you through to learn ajax CRUD in Laravel 9 Application with example.

We are going to create a Product table with name and its details columns. we will use yajra datatable package to list the products with pagination, filter (search) and sorting the columns with bootstrap 5 modal for creating and updating products.

Steps to Create Ajax CRUD Laravel 9 Application Example

  • Step 1: Installing a fresh Laravel 9 Application
  • Step 2: Installing Yajra Datatable Package
  • Step 3: Creating Database and Configuration
  • Step 4: Creating Migration Table
  • Step 5: Creating Routes
  • Step 6: Creating Controllers and Models
  • Step 7: Creating Blade Views Files
  • Step 8: Testing
  • Step 9: Conclusion

Also Read: How to get Country City Address from IP Address Laravel 9

Step 1: Installing a fresh Laravel 9 Application

First, We are going to install fresh new Laravel 9 Application. To install a Laravel Application run the following command in terminal.

composer create-project laravel/laravel ajax-crud-app

cd ajax-crud-app

Note :ajax-crud-app” is the Laravel application name we use.

Installing a fresh Laravel 9 Application
Installing a fresh Laravel 9 Application

Step 2: Installing Yajra Datatable Package

Now we are going to install Yajra Datatable Package. To install the Yajra Datatable Package run the following command in terminal.

composer require yajra/laravel-datatables-oracle
Installing Yajra Datatable Package
Installing Yajra Datatable Package

Now, Set providers and alias

.....
'providers' => [
	....
	Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
	....
	'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....

Step 3: Creating Database and Configuration

Next step is to create database and configure it. First go to phpmyadmin and create a new database with name “ajax-crud-app” you can use any name as you like.

 Creating Database
Creating Database

Also Read: Automatically Backup Database Laravel 9

Now, We are going to update the database details to our .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ajax-crud-app
DB_USERNAME=root
DB_PASSWORD=
Database Configuration to .env file
Database Configuration to .env file

Step 4: Creating Migration Table

We are creating CRUD application to create, update, delete the products so we need a product table. So in this step we are going to create a product table. We are using a artisan command to create product migration run the following command to create.

php artisan make:migration create_products_table --create=products

Now this products migration file can be found at “database/migrations”. Open the file update the following code to add name and detail field.

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }

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

Also Read: Create Livewire CRUD Application in Laravel 9 Example

Save the file and now run the migration with the following command.

php artisan migrate

Step 5: Creating Routes

Now, We are going to create resource route for products ajax CRUD application. So open “routes/web.php” and update the following code.

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::resource('products-ajax-crud', ProductAjaxController::class);
Creating Routes
Creating Routes

Step 6: Creating Controllers and Models

Also Read: Upload Images to Server PHP Tutorial (2022)

Next, We are going to create controllers and models for Products. First create a ProductAjaxController.php file inside app\Http\Controllers\ and add the following code.

<?php
           
namespace App\Http\Controllers;
            
use App\Models\Product;
use Illuminate\Http\Request;
use DataTables;
          
class ProductAjaxController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
     
        if ($request->ajax()) {
  
            $data = Product::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 editProduct">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 deleteProduct">Delete</a>';
    
                            return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
        
        return view('productAjax');
    }
       
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        Product::updateOrCreate([
                    'id' => $request->product_id
                ],
                [
                    'name' => $request->name, 
                    'detail' => $request->detail
                ]);        
     
        return response()->json(['success'=>'Product saved successfully.']);
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $product = Product::find($id);
        return response()->json($product);
    }
    
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Product::find($id)->delete();
      
        return response()->json(['success'=>'Product deleted successfully.']);
    }
}
Create Products Controller
Create Products Controller

Now create a Product.php file inside app/Models/ and add the following code inside it.

<?php
 
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Product extends Model
{
    use HasFactory;
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'name', 'detail'
    ];
}
Create Model
Create Model

Also Read: Laravel Load More Data on Scroll with jQuery and Ajax

Step 7: Creating Blade Views Files

Now, Last step is to create a blade view file to display the products. Create a productAjax.blade.php inside resources/views/ and add the following code.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Ajax CRUD Tutorial Example - LaravelTuts.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <!-- CSS only -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.12.1/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">

    <!-- JavaScript -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.12.1/js/dataTables.bootstrap5.min.js"></script>
</head>
<body>
    <section class="py-3 align-items-center d-flex rounded-0 mb-2" style="background:#1d3b53;">
        <!-- Main banner background image -->
        <div class="container">
            <div class="row">
                <div class="col-12 text-center">
                    <!-- Title -->
                    <h1 class="text-white">Laravel Ajax CRUD Tutorial Example</h1>
                    <p class="text-white mb-0">LaravelTuts.com</p>	
                </div>
            </div>
        </div>
    </section>

    <section>
        <div class="container">
            <ul class="nav nav-pills nav-pills-bg-soft justify-content-sm-end mb-4 ">
                <a class="btn btn-success" href="javascript:void(0)" id="createNewProduct"> Create New Product</a>
            </ul>
            <table class="table table-bordered data-table">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Name</th>
                        <th>Details</th>
                        <th width="280px">Action</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    <section>
     
    <div class="modal fade" id="ajaxModel" 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="productForm" name="productForm" class="form-horizontal">
                    <input type="hidden" name="product_id" id="product_id">
                        <div class="form-group">
                            <label for="name" class="col-sm-2 control-label">Name</label>
                            <div class="col-sm-12">
                                <input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required="">
                            </div>
                        </div>
        
                        <div class="form-group">
                            <label class="col-sm-2 control-label">Details</label>
                            <div class="col-sm-12">
                                <textarea id="detail" name="detail" required="" placeholder="Enter Details" class="form-control"></textarea>
                            </div>
                        </div>
            
                        <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-primary" id="saveBtn" value="create">Save changes
                        </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
      
<script type="text/javascript">
  $(function () {
      
    /*------------------------------------------
     --------------------------------------------
     Pass Header Token
     --------------------------------------------
     --------------------------------------------*/ 
    $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
    });
      
    /*------------------------------------------
    --------------------------------------------
    Render DataTable
    --------------------------------------------
    --------------------------------------------*/
    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('products-ajax-crud.index') }}",
        columns: [
            {data: 'DT_RowIndex', name: 'DT_RowIndex'},
            {data: 'name', name: 'name'},
            {data: 'detail', name: 'detail'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });
      
    /*------------------------------------------
    --------------------------------------------
    Click to Button
    --------------------------------------------
    --------------------------------------------*/
    $('#createNewProduct').click(function () {
        $('#saveBtn').val("create-product");
        $('#product_id').val('');
        $('#productForm').trigger("reset");
        $('#modelHeading').html("Create New Product");
        $('#ajaxModel').modal('show');
    });
      
    /*------------------------------------------
    --------------------------------------------
    Click to Edit Button
    --------------------------------------------
    --------------------------------------------*/
    $('body').on('click', '.editProduct', function () {
      var product_id = $(this).data('id');
      $.get("{{ route('products-ajax-crud.index') }}" +'/' + product_id +'/edit', function (data) {
          $('#modelHeading').html("Edit Product");
          $('#saveBtn').val("edit-user");
          $('#ajaxModel').modal('show');
          $('#product_id').val(data.id);
          $('#name').val(data.name);
          $('#detail').val(data.detail);
      })
    });
      
    /*------------------------------------------
    --------------------------------------------
    Create Product Code
    --------------------------------------------
    --------------------------------------------*/
    $('#saveBtn').click(function (e) {
        e.preventDefault();
        $(this).html('Sending..');
      
        $.ajax({
          data: $('#productForm').serialize(),
          url: "{{ route('products-ajax-crud.store') }}",
          type: "POST",
          dataType: 'json',
          success: function (data) {
       
              $('#productForm').trigger("reset");
              $('#ajaxModel').modal('hide');
              table.draw();
           
          },
          error: function (data) {
              console.log('Error:', data);
              $('#saveBtn').html('Save Changes');
          }
      });
    });
      
    /*------------------------------------------
    --------------------------------------------
    Delete Product Code
    --------------------------------------------
    --------------------------------------------*/
    $('body').on('click', '.deleteProduct', function () {
     
        var product_id = $(this).data("id");
        confirm("Are You sure want to delete !");
        
        $.ajax({
            type: "DELETE",
            url: "{{ route('products-ajax-crud.store') }}"+'/'+product_id,
            success: function (data) {
                table.draw();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });
       
  });
</script>
</html>

Step 8: Testing

Everything is done! Now its time to test the application. First start the server by run the following command:

php artisan serve

Now the following URL in any web browser.

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

Previews:

Products Lists:

Previews Products Lists - Create Ajax CRUD Laravel 9 Application Example
Previews Products Lists

Products Create:

Previews Products Create - Create Ajax CRUD Laravel 9 Application Example
Previews Products Create

Products Edit:

Previews Products Edit - Create Ajax CRUD Laravel 9 Application Example
Previews Products Edit

Products Pagination:

Previews Products Pagination - Create Ajax CRUD Laravel 9 Application Example
Previews Products Pagination

Products Delete:

Previews Products Delete - Create Ajax CRUD Laravel 9 Application Example
Previews Products Delete

Step 9: Conclusion

Today, We had learn How to Create Ajax CRUD Laravel 9 Application Example. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: Create Custom Helper in CodeIgniter (2022)

2 Comments

Leave a Reply