Welcome back to the Laravel E-Commerce Project Tutorial! In this video, we will learn about deleting a category.

Creating a New Function in AdminController

So, let's see how we can delete the category. Go to the Admin Controller and create a new function:


public function delete_category($id)
{
$category = Category::find($id);
if (File::exists(public_path('uploads/categories').'/'.$category->image)) {
File::delete(public_path('uploads/categories').'/'.$category->image);
}
$category->delete();
return redirect()->route('admin.categories')->with('status','Record has been deleted successfully !');
}

Creating the Route

Now, create a route for this. So, go to the web.php file and create a new route here:


Route::delete('/admin/category/{id}/delete',[AdminController::class,'delete_category'])->name('admin.category.delete');

Adding the Delete Link

Now, go to the categories.blade.php file and add the delete link here:


<td>
<div class=`list-icon-function`>
<form action=`{{route('admin.category.delete',['id'=>$category->id])}}` method=`POST`>
@csrf
@method('DELETE')
<div class=`item text-danger delete`>
<i class=`icon-trash-2`></i>
</div>
</form>
</div>
</td>

Adding Confirmation Before Deleting

After this, let's show the confirmation before deleting the category. So, after the content section directive, add the @push directive and add the following code:


@push('scripts')
<script>
$(function(){
$(`.delete`).on('click',function(e){
e.preventDefault();
var selectedForm = $(this).closest('form');
swal({
title: `Are you sure?`,
text: `You want to delete this record?`,
type: `warning`,
buttons: [`No!`, `Yes!`],
confirmButtonColor: '#dc3545'
}).then(function (result) {
if (result) {
selectedForm.submit();
}
});
});
});
</script>
@endpush

Checking the Result

Now, let's check. Refresh the page. Now, click on this delete link, and here is the confirmation box. Now, click on `Yes`, and you can see the category has been deleted.

So, in this way, you can delete the category.

That's all about deleting a category in the Laravel E-Commerce project.