onclick update database in laravel

Today, We want to share with you onclick update database in laravel.In this post we will show you Laravel Update User Status Using Toggle Button Example, hear for update database when user click on a link we will give you demo and example for implement.In this post, we will learn about Laravel 5/6/7 Change database column when button is clicked with an example.

onclick update database in laravel

There are the Following The simple About Ajax CRUD operations in laravel Full Information With Example and source code.

As I will cover this Post with live Working example to develop Insert Update and Delete record with AJAX in Laravel, so the Update database on button click? – PHP is used for this example is following below.

Laravel is a web application framework with expressive, elegant syntax.The PHP Framework for Web Artisans,freeing you to create without sweating the small things. CRUD Operation With Server Side.

Keywords : onclick ajax in laravel, how to insert data using ajax in laravel with datatables, onclick update database in php, laravel ajax update database, update data in laravel, insert data using ajax in laravel 5, update query on button click in php, how to update table in laravel

Insert Update and Delete record with AJAX in Laravel

1. Table structure

CREATE TABLE `members` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `member_name` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Database Configuration

Open .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=pakainfo
DB_USERNAME=root
DB_PASSWORD=

3. Model

Completed Code

<?php

namespace App;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class Task extends Model {

   public static function getmemberData($id=null){

     $value=DB::table('members')->orderBy('id', 'asc')->get(); 
     return $value;

   }

   public static function insertData($data){

     $value=DB::table('members')->where('member_name', $data['member_name'])->get();
     if($value->count() == 0){
       $insertid = DB::table('members')->insertGetId($data);
       return $insertid;
     }else{
       return 0;
     }

   }

   public static function updateData($id,$data){
      DB::table('members')->where('id', $id)->update($data);
   }

   public static function deleteData($id=0){
      DB::table('members')->where('id', '=', $id)->delete();
   }

}

4. Controller

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Task;

class TasksController extends Controller {
  public function index(){
    return view('index');
  }

  // Fetch records
  public function getMembers(){
    // Call getmemberData() method of Task Model
    $memberData['data'] = Task::getmemberData();

    echo json_encode($memberData);
    exit;
  }

  // Insert record
  public function addMember(Request $request){

    $name = $request->input('name');
    $member_name = $request->input('member_name');
    $email = $request->input('email');

    if($name !='' && $member_name !='' && $email != ''){
      $data = array('name'=>$name,"member_name"=>$member_name,"email"=>$email);

      // Call insertData() method of Task Model
      $value = Task::insertData($data);
      if($value){
        echo $value;
      }else{
        echo 0;
      }

    }else{
       echo 'Fill all fields.';
    }

    exit; 
  }

  // Update record
  public function updateMember(Request $request){

    $name = $request->input('name');
    $email = $request->input('email');
    $editid = $request->input('editid');

    if($name !='' && $email != ''){
      $data = array('name'=>$name,"email"=>$email);

      // Call updateData() method of Task Model
      Task::updateData($editid, $data);
      echo 'Update successfully.';
    }else{
      echo 'Fill all fields.';
    }

    exit; 
  }

  // Delete record
  public function deleteMember($id=0){
    // Call deleteData() method of Task Model
    Task::deleteData($id);

    echo "Delete successfully";
    exit;
  }
}

5. Route

Open router/web.php file.

<?php

Route::get('/', '[email protected]');
Route::get('/getMembers', '[email protected]');
Route::post('/addMember', '[email protected]');
Route::post('/updateMember', '[email protected]');
Route::get('/deleteMember/{id}', '[email protected]');

6. View

Create a new index.blade.php file in resources/views/ directory.

Read Also:  Laravel Many to many relationships with itself

<!DOCTYPE html>
<html>
  <head>
    <title>Insert Update and Delete record with AJAX in Laravel</title>
    <!-- provide the csrf token -->
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    
    <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> --> <!-- jQuery CDN -->
    <script src="{{asset('js/jquery-3.3.1.min.js')}}"></script>
  </head>
  <body>

    <table border='1' id='memberTable' style='border-collapse: collapse;'>
      <thead>
        <tr>
          <th>Membername</th>
          <th>Name</th>
          <th>Email</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><input type='text' id='member_name'></td>
          <td><input type='text' id='name' ></td>
          <td><input type='text' id='email' ></td>
          <td><input type='button' id='addmember' value='Add'></td>
        </tr>
      </tbody>
    </table>

<!-- Script -->
<script type='text/javascript'>
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

$(document).ready(function(){

  // Fetch records
  fetchRecords();

  // Add record
  $('#addmember').click(function(){

    var member_name = $('#member_name').val();
    var name = $('#name').val();
    var email = $('#email').val();

    if(member_name != '' && name != '' && email != ''){
      $.ajax({
        url: 'addMember',
        type: 'post',
        data: {_token: CSRF_TOKEN,member_name: member_name,name: name,email: email},
        success: function(response){

          if(response > 0){
            var id = response;
            var findnorecord = $('#memberTable tr.norecord').length;

            if(findnorecord > 0){
              $('#memberTable tr.norecord').remove();
            }
            var tr_str = "<tr>"+
            "<td align='center'><input type='text' value='" + member_name + "' id='member_name_"+id+"' disabled ></td>" +
            "<td align='center'><input type='text' value='" + name + "' id='name_"+id+"'></td>" +
            "<td align='center'><input type='email' value='" + email + "' id='email_"+id+"'></td>" +
            "<td align='center'><input type='button' value='Update' class='update' data-id='"+id+"' ><input type='button' value='Delete' class='delete' data-id='"+id+"' ></td>"+
            "</tr>";

            $("#memberTable tbody").append(tr_str);
          }else if(response == 0){
            alert('Membername already in use.');
          }else{
            alert(response);
          }

          // Empty the input fields
          $('#member_name').val('');
          $('#name').val('');
          $('#email').val('');
        }
      });
    }else{
      alert('Fill all fields');
    }
  });

});

// Update record
$(document).on("click", ".update" , function() {
  var edit_id = $(this).data('id');

  var name = $('#name_'+edit_id).val();
  var email = $('#email_'+edit_id).val();

  if(name != '' && email != ''){
    $.ajax({
      url: 'updateMember',
      type: 'post',
      data: {_token: CSRF_TOKEN,editid: edit_id,name: name,email: email},
      success: function(response){
        alert(response);
      }
    });
  }else{
    alert('Fill all fields');
  }
});

// Delete record
$(document).on("click", ".delete" , function() {
  var delete_id = $(this).data('id');
  var el = this;
  $.ajax({
    url: 'deleteMember/'+delete_id,
    type: 'get',
    success: function(response){
      $(el).closest( "tr" ).remove();
      alert(response);
    }
  });
});

// Fetch records
function fetchRecords(){
  $.ajax({
    url: 'getMembers',
    type: 'get',
    dataType: 'json',
    success: function(response){

      var len = 0;
      $('#memberTable tbody tr:not(:first)').empty(); // Empty <tbody>
      if(response['data'] != null){
        len = response['data'].length;
      }

      if(len > 0){
        for(var i=0; i<len; i++){

          var id = response['data'][i].id;
          var member_name = response['data'][i].member_name;
          var name = response['data'][i].name;
          var email = response['data'][i].email;

          var tr_str = "<tr>" +
          "<td align='center'><input type='text' value='" + member_name + "' id='member_name_"+id+"' disabled></td>" +
          "<td align='center'><input type='text' value='" + name + "' id='name_"+id+"'></td>" + 
          "<td align='center'><input type='email' value='" + email + "' id='email_"+id+"'></td>" +
          "<td align='center'><input type='button' value='Update' class='update' data-id='"+id+"' ><input type='button' value='Delete' class='delete' data-id='"+id+"' ></td>"+
          "</tr>";

          $("#memberTable tbody").append(tr_str);

        }
      }else{
        var tr_str = "<tr class='norecord'>" +
        "<td align='center' colspan='4'>No record found.</td>" +
        "</tr>";

        $("#memberTable tbody").append(tr_str);
      }

    }
  });
}
</script>

  </body>
</html>

Update database onclick using ajax call

use this jQuery

$(document).ready(function(){
    $('li').on('click', function(e){
        $.ajax({
            url: 'api/products/update/'+$(this).data('id'),
            method: 'GET'
        }).then(function(){
            alert('success');
        });
    }); 
})

Blade File Code

@foreach($products as $product)
    <li data-id='{!! $product->id !!}'>{!! $product->name !!}</li>
@endforeach

Web Programming Tutorials Example with Demo

Read :

Read Also:  Laravel 6 User Roles and Permissions Tutorial

Summary

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

I hope you get an idea about Update Model Status using Toggles in Laravel.
I would like to have feedback on my infinityknow.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. Read Also:  PHP Laravel Sessions Example Tutorial
  2. Read Also:  laravel 6 Retrieve data using jQuery Ajax
  3. Read Also:  Laravel Datatable Pagination Sorting and Search server side processing
  4. Read Also:  Laravel 5.7 Google reCAPTCHA Tutorial with Example
  5. Read Also:  how to insert data using ajax in laravel with datatables?
  6. Read Also:  Laravel Toggle Switch with Ajax Update Database
  7. Read Also:  How to get last inserted id in laravel 5.8?
  8. Read Also:  Laravel 5.7 Jquery Ajax CRUD(insert update delete)
  9. Read Also:  Laravel 6 Join Clause Example Tutorial
  10. Read Also:  Laravel 6 Get City Country By IP Address
CLOSEX