Laravel 11 E-Commerce Project

Laravel 11 E-Commerce Project - Admin Delete Coupon


Video Thumbnail

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

Step 1: Create a Function in the AdminController

First, let's create a new function in the AdminController for deleting a coupon:


public function delete_coupon($id)
{
        $coupon = Coupon::find($id);        
        $coupon->delete();
        return redirect()->route('admin.coupons')->with('status','Record has been deleted successfully !');
}

Step 2: Create a Route for the Function

Next, create a route for this function. Go to the web.php file and create a new route:


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

Step 3: Add a Delete Link

Now, go to the coupons.blade.php file and add a delete link inside the foreach loop:


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

Step 4: Add a Delete Confirmation

To show a delete confirmation, add the following code in the @push directive:


@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

Now it's done! Let's check it out. Refresh the page, click on the delete icon, and you will see a confirmation dialog. Click on `Yes` to delete the coupon.

In this way, you can delete a coupon.

That's all about deleting a coupon.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.