🚀 DevOps & SRE Certification Program 📅 Starting: 1st of Every Month 🤝 +91 8409492687 🔍 Contact@DevOpsSchool.com

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

How to Delete Multiple Records using Checkbox in Laravel?

It’s almost need to give feature for remove multiple records using checkbox, if you are developing e-commerce application or any big web application then you must give feature to delete multiple records.

So in this post, i will let you know how to delete multiple records with checkbox in laravel 5, laravel 6, laravel 7 and laravel 8 application. here i also give multiple delete and you can also delete single records. 

In this example, i simply created “products” table with id, name, details, created_at and updated_at columns. I also added mysql query for add dummy records. Here i use jquery for select all checkboxs and delete all records. So finally you have to follow some step and get the layout like as bellow.

Step 1: Create Project for this command

$ composer create-project --prefer-dist laravel/laravel Multiple_delete "5.8.*"

Step 2 : Go to laravel Project and .env file set msql name

Step 3 :  Create database

Step 4 : Create ProductController for this Command

$ php artisan make:controller Product

Step 5 : Create Product migration for this command

$ php artisan make:migration create_product_table

Step 5: Product migration add for this Product name and Product details

Step 6: Create products Table for database this command

$ php artisan migrate

Step 7: Add ProductController

Here, we will create new ProductController file to handle request of created three new route. In this Controller we define three method, index(), destroy() and deleteAll(). method will handle route request. So let’s create new controller and put code:

app/Http/Controllers/ProductController.php

<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Redirect;
use Session;
use DB;
class ProductController extends Controller
{
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$products = DB::table("products")->get();
return view('products',compact('products'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view("create");
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'product_name'=>'required',
'product_detailes'=>'required',
]);
// store
$data = new Product;
$data->product_name = Input::get('product_name');
$data->product_detailes = Input::get('product_detailes');
$data->save();
// redirect
return Redirect::to('myproducts')->with('success', 'Product Added successfully.');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
DB::table("products")->delete($id);
return response()->json(['success'=>"Product Deleted successfully.", 'tr'=>'tr_'.$id]);
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function deleteAll(Request $request)
{
$ids = $request->ids;
DB::table("products")->whereIn('id',explode(",",$ids))->delete();
return response()->json(['success'=>"Products Deleted successfully."]);
}
}

Step 8: Create new Routes

In this step, we are doing from scratch so we will add three routes, one for display data and another for delete request, then third for remove all selected data. So you have to simply add three new routes in your laravel application.

routes/web.php

Step 9 – Set Data in View File in Add Product details

This is the last step in the Laravel 5.8 Crud application, and in this step, we have to set data in the view file which has been store under the resources/views folder because this view file has received data from the controller method, so here we have to set data in the view file. Below you can file all view file which has been used in the Crud application, and you can also find how data have been set and how to make a form in Add Product details

resources/views/sorces.blade.php

<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div class="container">
<br />
<h3 align="center">Add Product Detailes</h3>
<br />
@yield('main')
</div>
</body>
</html>

Step 10: Add Blade File

In last step, we will create products.blade.php file and write code of jquery for delete and delete all function. So let’s create products.blade.php file and put bellow code:

resources/views/products.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Laravel 5 - Multiple delete records with checkbox example</title>
<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>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div class="container">
<h3>Laravel 5 - Multiple delete records with checkbox example</h3>
<div>
<a href="{{route('create')}}" class="btn btn-success ">Add Product</a>
</div>
<button style="margin-bottom: 10px" class="btn btn-primary delete_all" data-url="{{ url('myproductsDeleteAll') }}">Delete All Selected</button>
<table class="table table-bordered">
<tr>
<th width="50px"><input type="checkbox" id="master"></th>
<th width="80px">No</th>
<th>Product Name</th>
<th>Product Details</th>
<th width="100px">Action</th>
</tr>
@if($products->count())
@foreach($products as $key => $product)
<tr id="tr_{{$product->id}}">
<td><input type="checkbox" class="sub_chk" data-id="{{$product->id}}"></td>
<td>{{ ++$key }}</td>
<td>{{ $product->product_name }}</td>
<td>{{ $product->product_detailes }}</td>
<td>
<a href="{{ url('myproducts',$product->id) }}" class="btn btn-danger btn-sm"
data-tr="tr_{{$product->id}}"
data-toggle="confirmation"
data-btn-ok-label="Delete" data-btn-ok-icon="fa fa-remove"
data-btn-ok-class="btn btn-sm btn-danger"
data-btn-cancel-label="Cancel"
data-btn-cancel-icon="fa fa-chevron-circle-left"
data-btn-cancel-class="btn btn-sm btn-default"
data-title="Are you sure you want to delete ?"
data-placement="left" data-singleton="true">
Delete
</a>
</td>
</tr>
@endforeach
@endif
</table>
</div> <!-- container / end -->
</body>
<script type="text/javascript">
$(document).ready(function () {
$('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
} else {
$(".sub_chk").prop('checked',false);
}
});
$('.delete_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
if(allVals.length <=0)
{
alert("Please select row.");
} else {
var check = confirm("Are you sure you want to delete this row?");
if(check == true){
var join_selected_values = allVals.join(",");
$.ajax({
url: $(this).data('url'),
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+join_selected_values,
success: function (data) {
if (data['success']) {
$(".sub_chk:checked").each(function() {
$(this).parents("tr").remove();
});
alert(data['success']);
} else if (data['error']) {
alert(data['error']);
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
$.each(allVals, function( index, value ) {
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
onConfirm: function (event, element) {
element.trigger('confirm');
}
});
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success']) {
$("#" + data['tr']).slideUp("slow");
alert(data['success']);
} else if (data['error']) {
alert(data['error']);
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
});
</script>
</html>

Step 10: Add Blade File

create() – This method has been used for load the create.blade.php file. In this file, users can find a form for insert new records and filling data insert data requests will be sent to the store() method of CrudsController.php controller class.

resources/views/create.blade.php

@extends('sorces')
@section('main')
{{-- messsage pop up open --}}
@if(session()->get('success'))
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ session()->get('success') }}
</div>
@endif
<div class="col-12">
@if(session()->get('danger'))
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ session()->get('danger') }}
</div>
@endif
</div>
@if(count($errors) > 0)
<div class="row">
<div class="col-12 error">
<ul>
@foreach($errors->all() as $error)
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
<p class="text-center"> {{$error}}</p>
</div>
@endforeach
</ul>
</div>
@endif
{{-- messsage pop up close --}}
<div class="container">
<div class="row">
<div class="card-body">
<form method="post" action="{{ route('store') }}" enctype="multipart/form-data">
@csrf
<div class="form-group">
<h5 class="col-md-4 ">Product Name</h5>
<div class="col-md-8">
<input type="text" name="product_name" class="form-control" required />
</div>
</div>
<div class="form-group">
<h5 class="col-md-4">Product Detailes</h5>
<div class="col-md-8">
<input type="text" name="product_detailes" class="form-control" required />
</div>
</div><br>
<div class="form-group ml-4">
<div class="col-md-4">
<div class="col-md-8">
<input type="submit" name="add product" class="btn btn-primary input-lg"
value="Add product" />
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.