Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
November 21, 2023
The purpose of this blog is to document the steps for implementing Sweet Alert, a JavaScript library by RealRashid, to confirm the deletion of a record in a Laravel controller’s destroy() method.
Step 1
Include ‘sweetalert::alert’ in the master layout using below following line:
@include('sweetalert::alert');
Then, run the following command to publish the package assets:
php artisan sweetalert:publish
Step 2
Create a controller with resource perameter using the following command:
php artisan make:controller productController --resource
That generate the all the basic functions for CRUD operation.
Step 3
Add the following code in the index method of the controller:
public function index(){ $title = 'Delete Product!'; $text = "Are you sure you want to delete?"; confirmDelete($title, $text); $products = product::select('id','title','vendor','type')->limit(10)->get(); return view('products.list',compact('products')); }
Then, add the attribute data-confirm-delete=”true” to view file’s delete button :
<a href="{{ route('product.destroy', $product->id) }}" class="btn btn-danger" data-confirm-delete="true">Delete</a>
After applying this attribute to the anchor tag, when the user click on this anchor tag, the Sweet Alert confirmation popup will appear. if user confirm this action, they will be redirect to the destroy URL.
Step 4
After beging redirected to the destroy method, you have to delete the record from database using the following code:
public function destroy(string $id){ $product = product::find($id); if ($product->delete()){ Alert::success('Deleted', 'Product Deleted successfully'); } return redirect()->route('product.index'); }