Home Ajax Laravel Ajax PUT Request Example Tutorial

Laravel Ajax PUT Request Example Tutorial

by Shahriar Sagor
Laravel Ajax PUT Request
Laravel Ajax PUT Request

Today now in this short tutorial i will cover an laravel ajax put request example. We can see in ajax put request in laravel example. So let’s discuss about the ajax patch request also with parameters laravel. if you have any question about the laravel ajax put the request also with parameter then here I will give simple an example also with solution. So let’s see the bellow example laravel ajax put request data.

Now in this example, i will create a list of users with an edit button. When we are click on the edit button then i will open the model with the name and email input and then i will save the data by using the ajax put method. We can also edit data by using jquery ajax get in laravel 6, laravel 7, laravel 8 and laravel 9 versions as well.

Let’s follow the below steps:

Step 1: Install Laravel

This is a optional; however, if we have not created the laravel application, then we may go ahead and need to execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create Dummy Users

Here, i will create some dummy records on users table and then import them.

so let’s need to run the following commands:

Create Dummy Records:

php artisan tinker
User::factory()->count(20)->create()

Step 3: Create UserController Controller

Now In this point, now we need to create a new controller as UserController. So In this controller, i will add index and show method, on that will be return users with filter.

Let’s update the following code to our controller file:

app/Http/Controllers/UserController.php

<?php
   
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\User;
    
class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {        
        $users = User::paginate(10);
 
        return view('users', compact('users'));
    }
 
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        User::find($id)->update([
            'name' => $request->name,
            'email' => $request->email
        ]);
        return response()->json(['success'=>'User Updated Successfully!']);
    }
}

Step 4: Add Route

Now in this is step we have to create a route for the listing users and put route. So need to open our “routes/web.php” file and then add the following route.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
  
/*
|--------------------------------------------------------------------------
| 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('users', [UserController::class, 'index']);
Route::put('users/{id}', [UserController::class, 'update'])->name('users.update');

Step 5: Create View

Now in last step, so let’s create the users.blade.php(resources/views/users.blade.php) for the layout and here i will write the design code here and just put following code:

resources/views/users.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Ajax PUT Request Example  - Codingspoint.com</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
        
<div class="container">
    <h1>Laravel Ajax PUT Request Example - Codingspoint.com</h1>
    
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach($users as $user)
            <tr data-id="{{ $user->id }}">
                <td>{{ $user->id }}</td>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
                <td>
                    <a 
                        href="javascript:void(0)" 
                        id="edit-user" 
                        class="btn btn-primary"
                        >Edit</a>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>
 
</div>
 
<!-- Modal -->
  
<div class="modal fade" id="userEditModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
  
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Edit User</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
  
      </div>
  
      <div class="modal-body">
        <input type="hidden" id="user-id" name="id"></span>
        <p><strong>Name:</strong> <br/> <input type="text" name="name" id="user-name" class="form-control"></span></p>
        <p><strong>Email:</strong> <br/> <input type="email" name="email" id="user-email" class="form-control"></span></p>
      </div>
  
      <div class="modal-footer">
        <button type="button" class="btn btn-success" id="user-update">Update</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
      
</body>
 
<script type="text/javascript">
      
    $(document).ready(function () {
  
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
  
        /*------------------------------------------
        --------------------------------------------
        When click user on Edit Button
        --------------------------------------------
        --------------------------------------------*/
        $('body').on('click', '#edit-user', function () {
   
            var userURL = $(this).data('url');
  
            $('#userEditModal').modal('show');
            $('#user-id').val($(this).parents("tr").find("td:nth-child(1)").text());
            $('#user-name').val($(this).parents("tr").find("td:nth-child(2)").text());
            $('#user-email').val($(this).parents("tr").find("td:nth-child(3)").text());
 
       });
      
        /*------------------------------------------
        --------------------------------------------
        When click user on Show Button
        --------------------------------------------
        --------------------------------------------*/
        $('body').on('click', '#user-update', function () {
   
            var id = $('#user-id').val();
            var name = $('#user-name').val();
            var email = $('#user-email').val();
  
            $.ajax({
                url: '/users/' + id,
                type: 'PUT',
                dataType: 'json',
                data: { name: name, email: email},
                success: function(data) {
                    $('#userEditModal').modal('hide');
                    alert(data.success);
  
                    $("tr[data-id="+id+"]").find("td:nth-child(2)").text(name);
                    $("tr[data-id="+id+"]").find("td:nth-child(3)").text(email);
                }
            });
  
       });
         
    });
    
</script>
      
</html>

Run Laravel App:

That’s good all the required steps have been done. So now we have to type the given below command and then hit enter to run the Laravel appliction:

php artisan serve

Read Also: php artisan serve not working in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like