Delete multiple records using ajax tutorial in laravel 11
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
$users = User::all();
return view("users", compact("users"));
}
public function deleteUser(Request $request)
{
if (isset($request->ids)) {
User::whereIn("id", $request->ids)->delete();
return response()->json(["success" => true, "msg" => "Users deleted successfully", "ids" => $request->ids]);
}
return response()->json(["success" => false, "msg" => "Users ids not found"]);
}
}
Above File is app\Http\Controllers\UserController.php FileBelow File is app\Models\User.php File
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
public $timestamps = false;
protected $table = "users";
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email'
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}
Below File is database\json\users.json File
[
{
"name": "hariom",
"email": "hariom@gmail.com"
},
{
"name": "Shree",
"email": "shree@gmail.com"
},
{
"name": "Sandeep",
"email": "sandeep@gmail.com"
},
{
"name": "Ram",
"email": "ram@gmail.com"
},
{
"name": "Shivanya",
"email": "shivanya@gmail.com"
},
{
"name": "Guru Prasad",
"email": "guru@gmail.com"
},
{
"name": "Shresth",
"email": "shresth@gmail.com"
},
{
"name": "Kanti",
"email": "kanti@gmail.com"
},
{
"name": "Kuldeep",
"email": "kuldeep@gmail.com"
},
{
"name": "Shyam",
"email": "shyam@gmail.com"
},
{
"name": "Hari",
"email": "hari@gmail.com"
},
{
"name": "Darshan",
"email": "darshan@gmail.com"
},
{
"name": "love",
"email": "love@gmail.com"
}
]
Below File is database\migrations\2025_01_08_120440_create_users_table File
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string("name");
$table->string("email");
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};
Below File is database\seeders\DatabaseSeeder.php File
<?php
namespace Database\Seeders;
use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
// User::factory(10)->create();
// User::factory()->create([
// 'name' => 'Test User',
// 'email' => 'test@example.com',
// ]);
$this->call([
UserSeeder::class
]);
}
}
Below File is database\seeders\UserSeeder.php File
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$json = File::get(path: "database\json\users.json");
$users = collect(json_decode($json));
$users->each(function ($user) {
User::create([
"name" => $user->name,
"email" => $user->email
]);
});
}
}
Below File is resources\views\users.blade.php File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Users</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-8">
<div class="card">
<div class="card-header">
<h4>Users Data</h4>
</div>
<div class="card-body">
<form id="formDelete" action="" method="POST">
@csrf
<table class="table table-bordered table-striped table-hovered">
<thead>
<th>Select</th>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</thead>
@if(count($users) > 0)
@foreach($users as $data)
<tbody>
<tr class="{{ $data->id }}">
<td>
<input type="checkbox" name="ids[{{ $data->id }}]" value="{{ $data->id }}"/>
</td>
<td>{{ $data->id }}</td>
<td>{{ $data->name }}</td>
<td>{{ $data->email }}</td>
</tr>
</tbody>
@endforeach
@else
<tr>
<td colspan="4" class="text-center fw-bold text-danger">Users not found</td>
</tr>
@endif
</table><br>
<input type="submit" value="Delete User" class="btn btn-danger"/>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#formDelete").submit(function(e){
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
url:"{{ route('deleteUser') }}",
type:"POST",
data:formData,
success:function(data){
if(data.success == true) {
var ids = data.ids;
$.each(data.ids, function (i,val) {
$("."+val).remove();
});
}
}
});
});
});
</script>
</body>
</html>
Below File is routes\web.php File
<?php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::controller(UserController::class)->group(function () {
Route::get("/users", "index")->name("users");
Route::post("/delete-user", "deleteUser")->name("deleteUser");
});
.png)
.png)
Comments
Post a Comment