Laravel AJAX Insert Update Delete (CRUD) Example Tutorial

Uncategorized

Today, We want to share with you Laravel AJAX Insert Update Delete (CRUD) Example Tutorial From Scratch.In this post we will show you Laravel 5 Ajax CRUD example for web application without page refresh, hear for Simple PHP Jquery Ajax CRUD(insert update delete) tutorial example with source code we will give you demo and example for implement.In this post, we will learn about Laravel Jquery Ajax CRUD (insert update delete) Tutorial From Scratch with an example.

List of all Google Adsense, VueJS, AngularJS, PHP, Laravel Examples.

Laravel AJAX Insert Update Delete (CRUD) Example Tutorial From Scratch

There are the Following The simple About Laravel AJAX Insert Update Delete (CRUD) Example Tutorial From Scratch Full Information With Example and source code.

As I will cover this Post with live Working example to develop Ajax CRUD operations in laravel, so the some Insert Update and Delete record with AJAX in Laravel for this example is following below.

Step 1: Install Laravel

first of all simple Install Laravel Application

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

Step 2: Create a Member Table and Model

Laravel simple create_members_table to Generated Migration

php artisan make:migration create_members_table

path : store file -> database/migrations

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMembersTable extends Migration
{
    public function up()
    {
        Schema::create('members', function (Blueprint $table) {
            $table->increments('id');
            $table->string('member_name');
            $table->text('member_address');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::drop("members");
    }
}

Now run below command to create a member table.

php artisan migrate

Member Model

namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
    public $fillable = ['member_name','member_address'];
}

Step 3: Create Laravel blade View files

resources/views/ajax/index.blade.php

  
   <title>Laravel Jquery Ajax CRUD (insert update delete) Example Tutorial From Scratch</title>
    
  

<div class="container">
<h1>Insert Update and Delete record with AJAX in Laravel</h1>
<div class="panel panel-primary">
 <div class="panel-heading">Laravel Jquery Ajax CRUD (insert update delete) Example Tutorial From Scratch
 <button id="btn_add" name="btn_add" class="btn btn-default pull-right">Add New Member</button>
    </div>
      <div class="panel-body">
       <table class="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Member Name</th>
            <th>Member Address</th>
            <th>Actions</th>
          </tr>
         </thead>
         <tbody id="members-list">
           @foreach ($members as $member)
            <tr>id}}">
             <td>{{$member->id}}</td>
             <td>{{$member->member_name}}</td>
             <td>{{$member->member_address}}</td>
              <td>
              <button class="btn btn-warning btn-detail open_modal">id}}">Edit</button>
              <button class="btn btn-danger btn-delete delete-member">id}}">Delete</button>
              </td>
            </tr>
            @endforeach
        </tbody>
        </table>
       </div>
       </div>
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog">
           <div class="modal-content">
             <div class="modal-header">
             <button type="button" class="close"><span>×</span></button>
                <h4 class="modal-title" id="myModalLabel">Member</h4>
            </div>
            <div class="modal-body">
            <form id="frmMembers" name="frmMembers" class="form-horizontal">
                <div class="form-group error">
                 <label for="inputName" class="col-sm-3 control-label">Member Name</label>
                   <div class="col-sm-9">
                    
                   </div>
                   </div>
                 <div class="form-group">
                 <label for="inputDetail" class="col-sm-3 control-label">Member Address</label>
                    <div class="col-sm-9">
                    
                    </div>
                </div>
            </form>
            </div>
            <div class="modal-footer">
            <button type="button" class="btn btn-primary" id="btn-save" value="add">Save changes</button>
            
            </div>
        </div>
      </div>
  </div>
</div>
    
    
    
    


Step4: Include JS file

public/js/ajaxscript.js

var url = "http://localhost:8080/membersapp/public/memberajaxCRUD";
    //display modal form for member editing
    $(document).on('click','.open_modal',function(){
        var member_id = $(this).val();

        $.get(url + '/' + member_id, function (data) {
            //success data
            console.log(data);
            $('#member_id').val(data.id);
            $('#member_name').val(data.member_name);
            $('#member_address').val(data.member_address);
            $('#btn-save').val("update");
            $('#myModal').modal('show');
        })
    });
    //display modal form for creating new member
    $('#btn_add').click(function(){
        $('#btn-save').val("add");
        $('#frmMembers').trigger("reset");
        $('#myModal').modal('show');
    });
    //delete member and remove it from list
    $(document).on('click','.delete-member',function(){
        var member_id = $(this).val();
         $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
        })
        $.ajax({
            type: "DELETE",
            url: url + '/' + member_id,
            success: function (data) {
                console.log(data);
                $("#member" + member_id).remove();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });
    //create new member / update existing member
    $("#btn-save").click(function (e) {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
        })
        e.preventDefault();
        var formData = {
            name: $('#member_name').val(),
            details: $('#member_address').val(),
        }
        //used to determine the http verb to use [add=POST], [update=PUT]
        var state = $('#btn-save').val();
        var type = "POST"; //for creating new resource
        var member_id = $('#member_id').val();;
        var my_url = url;
        if (state == "update"){
            type = "PUT"; //for updating existing resource
            my_url += '/' + member_id;
        }
        console.log(formData);
        $.ajax({
            type: type,
            url: my_url,
            data: formData,
            dataType: 'json',
            success: function (data) {
                console.log(data);
                var member = '<tr id="member' + data.id + '"><td>' + data.id + '</td><td>' + data.member_name + '</td><td>' + data.member_address + '</td>';
                member += '<td><button class="btn btn-warning btn-detail open_modal" value="' + data.id + '">Edit</button>';
                member += ' <button class="btn btn-danger btn-delete delete-member" value="' + data.id + '">Delete</button></td></tr>';
                if (state == "add"){ //if user added a new record
                    $('#members-list').append(member);
                }else{ //if user updated an existing record
                    $("#member" + member_id).replaceWith( member );
                }
                $('#frmMembers').trigger("reset");
                $('#myModal').modal('hide')
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });

Step 5: Add Laravel Routes

Laravel Member Crud Ajax Methods with Routing

use Illuminate\Http\Request;
Route::get('memberajaxCRUD', function () {
    $members = App\Member::all();
    return view('ajax.index')->with('members',$members);
});
Route::get('memberajaxCRUD/{member_id?}',function($member_id){
    $member = App\Member::find($member_id);
    return response()->json($member);
});
Route::post('memberajaxCRUD',function(Request $request){
    $member = App\Member::create($request->input());
    return response()->json($member);
});
Route::put('memberajaxCRUD/{member_id?}',function(Request $request,$member_id){
    $member = App\Member::find($member_id);
    $member->name = $request->name;
    $member->details = $request->details;
    $member->save();
    return response()->json($member);
});
Route::delete('memberajaxCRUD/{member_id?}',function($member_id){
    $member = App\Member::destroy($member_id);
    return response()->json($member);
});

Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Laravel AJAX Insert Update Delete (CRUD) Example Tutorial From Scratch.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   PHP MySQL Dynamic Treeview using jQuery Ajax Example
  2.   How to Get current Logged User Details in Laravel 5.8?
  3.   Simple Jquery Popup Onload Example
  4.   PHP connect Azure SQL Server Databases
  5.   Redirect to custom page after plugin activation
  6.   VueJS Disable enable Selector Examples
  7.   Redirect to custom page after plugin activation
  8.   PHP connect Azure SQL Server Databases
  9.   How to Get current Logged User Details in Laravel 5.8?
  10.   Simple Jquery Popup Onload Example

Leave a Reply

Your email address will not be published. Required fields are marked *