Laravel 11 E-Commerce - Admin Delete Brand

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

Creating a Function in AdminController

Let's see how we can delete a brand. First, go to the AdminController and create a function:


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

Creating the Route

Now, create a route for this. Go to the web.php file and create the route:


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

Adding the Delete Link

Now, go to the brands.blade.php file and add the link for deleting the brand:

For deleting the brand, we have to make a Delete request. So, in this link, add the form and set the method post, @csrf directive, and @method("DELETE") directive. Now, add the action and also pass the brand id as a parameter as follows:


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

Displaying the Confirmation Message

Now, before deleting the record, let's display the confirmation message. For that, let's show an alert message. For that, I have already added the Sweet Alert JS library. So, let's call the Sweet Alert here:


@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, everything is done. So, let's check this. Refresh the page, and now let's delete this brand. So, click here, and you can see the confirmation box. If I click on no, then the record is not deleted. If I click on yes, you can see the record has been deleted.

So, in this way, you can create the layout and implement the HTML template.

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