Laravel Delete Multiple Records Example; in this tutorial, you will learn how to delete Multiple Records using Checkbox in Laravel using jQuery and AJAX.
More then times we need to bulk select the rows (records) and archive or delete the multiple data from database. In table records we add the checkboxes and give select multiple records to one click functinality to user.
How to Delete Multiple Records Using Checkbox in Laravel
Follow to the following steps to implement How to dleete multiple records using checkbox funcationality in laravel 9 apps:
- Step 1: Download Laravel App
- Step 2: Set up Database
- Step 3: Create Model and Migration
- Step 4: Make Routes
- Step 5: Create Controller
- Step 6: Create View File
- Step 7: Run Development Server
Download laravel APP
Let’s invoke the following command in the terminal to install a brand new Laravel application.
composer create-project laravel/laravel laravel-app --prefer-dist
Next, get into the project directory:
cd laravel-app
Skip this step, if you have already installed the app.
Set Up Database
Add database name, username and password in .env file; it sustains the consensus between laravel and database.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Create Model and Migration
To make the multiple records deleting functinality, we will have to create the Post model by executing the below command.
php artisan make:model Post -m
After executing the above command, you will see the archetype of posts migration file in database\migrations\2021_09_26_072241_create_posts_table.php. Here, you have to add some values to create the internal coherence using Model.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
Then, run the migration by using the below command.
php artisan migrate
Next, create the app/Models/Post.php file and register the following values inside the $fillable
array.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title', 'description'
];
}
Add Routes
Now, we will define WEB routes. Go to routes/web.php file and declare the foundational code.
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
Route::get('posts/{id}', [PostController::class, 'destroy'])->name('posts.delete');
Route::delete('posts/deleteAll', [PostController::class, 'deleteAll'])->name('posts.deleteall');
Route::get('posts', [PostController::class, 'index'])->name('posts.index');
Create Controller
Create a controller by using the following command.
php artisan make:Controller PostController
Add the following code in app\Http\Controllers\PostController.php file.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
public function index()
{
$posts = Post::paginate(10);
return view('posts',compact('posts'));
}
public function destroy($id)
{
Post::find($id)->delete();
return back()->with('success', 'post delted successfully');
}
public function deleteAll(Request $request)
{
Post::whereIn('id',explode("," , $request->ids))->delete();
return response()->json(['success'=>"Products Deleted successfully."]);
}
}
Create Blade View File
Theoretically, we have reached almost the last step of this tutorial. First, create resources/views/posts.blade.php file, then add the following code.
<!DOCTYPE html>
<html>
<head>
<title>Laravel Delete Multiple records with checkbox example</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-confirmation/1.0.5/bootstrap-confirmation.min.js"></script>
</head>
<body>
<div class="container">
<h3>Laravel 9 Delete Multiple records with checkbox example</h3>
<button style="margin-bottom: 10px" class="btn btn-primary delete-all-posts pull-right" data-url="{{ route('posts.deleteall') }}">Delete All Posts</button>
<table class="table table-bordered">
<tr>
<th width="50px">
<input type="checkbox" id="deleteAllPost">
</th>
<th width="80px">No</th>
<th>Name</th>
<th>Details</th>
<th width="100px">Action</th>
</tr>
@if($posts->count())
@foreach($posts as $key => $post)
<tr id="tr_{{$post->id}}">
<td><input type="checkbox" class="sub_chk" data-id="{{$post->id}}"></td>
<td>{{ ++$key }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->description }}</td>
<td><a class="btn btn-danger btn-sm" href="{{ route('posts.delete', $post->id) }}">Delete</a></td>
</tr>
@endforeach
@endif
</table>
</div>
</body>
<script type="text/javascript">
$(document).ready(function () {
$('#deleteAllPost').on('click', function(e) {
if ($(this).is(':checked',true)) {
$(".sub_chk").prop('checked', true);
} else {
$(".sub_chk").prop('checked',false);
}
});
$('.delete-all-posts').on('click', function(e) {
let allPosts = [];
$(".sub_chk:checked").each(function() {
allPosts.push($(this).attr('data-id'));
});
if (allPosts.length <= 0 ) {
alert("Please select atleast one checkbox.");
} else {
let check = confirm("Are you sure you want to delete this record?");
if(check == true) {
let post_ids = allPosts.join(",");
$.ajax({
url: $(this).data('url'),
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+post_ids,
success: function (data) {
if (data['success']) {
alert(data['success']);
location.reload();
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
}
}
});
});
</script>
</html>
Generate Fake Records for Testing
For testing perpuse we need to generate dummy (fake) data using faker or factory laravel, we alaredy explain how to generate fake data in laravel app using faker and factory.
See Here: Generate Fake Data using Faker and Factory in Laravel
Run Development Server and Test
Finally, we have gone through each and every imperative respectively. Now, Its time to test out what we have built.
Run the following command to start the laravel app.
php artisan serve
Open the following URL in the browser:
http://localhost:8000/posts
Eventually, we have completed the Laravel 9 Delete multiple records using checkbox Tutorial. In this tutorial, we have shed light on every aspect needed to build how to delete multiple records using checkbox select.