Delete Operation – Laravel

Delete of any row from the list/table is done by using JavaScript.  To delete we must take care of following things:

  • Views ===> Delete button
  • Views ===> Form with action, method and id
  • Views ===> JavaScript to be triggered when delete button is clicked
  • Controller ===> Destroy function soft/hard delete. Return response to json

Delete Button

<a style="color: red !important" class="red btn-delete"  href="javascript:void(0)" data-id="{{ $test->id }}" ">
   <i class="ace-icon fa fa-trash-o bigger-130"></i>
</a>

Form  with link for the delete button to pass

<form action="{{ route('admin.testimonial.destroy','yyy')  }}" method="post" id="delete-form">

JavaScript Code 

<script>
$(function(){
          $(document).on('click','.btn-delete',function(e){
			var conf = confirm("Are you sure to delete this item...");
			 if(conf === true){
				var id = $(this).attr('data-id');
				 var pos_url = $("#delete-form").attr('action');
				var url = pos_url.replace('yyy',id);
					 $.ajax({
					 type:'POST',
					 data:{'_token':"{{ csrf_token() }}",'_method':'DELETE'},
					 url:url,
				 success:function(res,responseText,jqxhr){
				
							 if(jqxhr.status === 200){
									 window.location.reload(true);
							 }
					 },
					 error:function(res,responseText,jqxhr,errorStatus){
							 console.error(res);
					 }
				 });
			 }
				e.preventDefault();
			});
})
</script>

Controller ==> Destroy i.e. Delete

public function destroy($id)
    {
        $testimonial = Testimonial::find($id);
        
        $file = $testimonial->image;
        if(file_exists($file))
        {
            unlink($file);  // Delete file      
        }
       
             $testimonial->delete();
        die;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *