Remove Record no Reload Page using Ajax in Laravel

Sovary June 27, 2022 893
4 minutes read

We will make a short example using jQuery Ajax make request to delete a record in Laravel. In Laravel 5, Laravel 6, Laravel 7, Laravel 8 and Laravel 9 will work the same when you understand how backend Laravel accept the request. I will show example with Jquery Ajax make request from client and accept the request with Laravel 9.

laravel 9 ajax jquery remove record example

The following steps we will create a view file and write Jquery Ajax make request to server which is required to pass id of record and csrf token. By default CSRF is generate to verify that the person actually making the requests to the application. Then we will insert a delete route with controller class and method to point the submit request.

Ajax Delete Record without Refresh Page

This instruction are following steps to completed the mission today.

  • Step 1 - Install Laravel 9 & Setup Database
  • Step 2 - Create View & Ajax Request
  • Step 3 - Insert Route
  • Step 4 - Create Model & Migration
  • Step 5 - Create Controller
  • Step 6 - Generate Fake Data for Testing
  • Step 7 - Run Laravel Server

 

Step 1 - Install Laravel 9 & Setup Database

You have to installed Laravel framework. Read this to know how to install Laravel project with database.

Step 2 - Create View & Ajax Request

We are going to create simple HTML file with no design and write only jQuery Ajax request. We have to submit with CRSF token unless your server won't received the request.

Create file resources -> views -> index.blade.php

<!DOCTYPE html>
<html>
<body>

<h1>Sample Ajax Remove Data - cambotutorial.com</h1>

<button type="button" id="btn_remove">Remove</button>

</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$("#btn_remove").click(function()
{
    $.ajax(
      {
        url: "{{route('post.destroy',$post->id)}}",
        method: 'DELETE',
        data: {
          "id": {{$user->id}},
          "_token": "{{ csrf_token() }}"
        },
        success: function (resp)
        {
          alert(resp["success"]);
        },
        error: function(e)
        {
          console.log(e); 
        }
    });
});
</script>
</html>

 

Step 3 - Insert Route

Open file routes -> web.php

<?php

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

/*
|--------------------------------------------------------------------------
| 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('/', [PostController::class, 'index']);
Route::delete('/post/{id}', [PostController::class, 'destroy'])->name("post.destroy");

Step 4 - Create Model & Migration

Create Model

To generate migration file at the same time generate the model, you may use the --migration or -m option

php artisan make:model Post -m

Open file app -> models -> post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'slug', 'body'
    ];
}

Update Migration

Open file database -> migrations -> 2022_06_11_033722_create_posts_table.php

<?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('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug');
            $table->text('body');
            $table->timestamps();
        });
    }

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

Before run migration command, make sure you have updated database connection in .env file. To run migration by below command

php artisan migrate

 

Step 5 - Create Controller

Now we are going to create controller named PostController and write 2 methods to handle delete request and render the webpage. Following command to create controller and update code below.

php artisan make:controller PostController

Open file app -> Http -> Controllers -> PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
  // Render index page
  public function index()
  {
    return view("index");
  }
  /**
  * Remove the specified resource from storage.
  *
  * @param  $id
  * @return \Illuminate\Http\Response
  */
  public function destroy($id)
  {  
      Post::find($id)->delete();  
      return response()->json(['success' => 'Post deleted successfully!']);
  }
}

 

 

Step 6 - Generate Fake Data for Testing

If you have existing data in your table you might skip this step, for testing purpose to generate dummy data you can read following article I have completely write a tutorial. Click for Read

Step 7 - Run Laravel Server

Finally, run server developement by following command

php artisan serve

Open URL http://localhost:8000/ you will see very simple page with a button. Click a button to make Ajax request delete record.

Hope this tutorial help you to finished the project. Have a nice day !

 

You might Also Like:

JQuery  Laravel  PHP  Ajax  Laravel 9 
Author

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him