Ajax code to delete file in laravel

2019-09-17 12:33:28 Dinesh Mishra Laravel

Deleting a file from public directory in Laravel

Below is a simple code to unlink a file in laravel.

AJAX Code in your view file

var CSRF_TOKEN  =  "{{csrf_token()}}";
var postData ={
                    _token :CSRF_TOKEN,
                     url'file_name'
              }
jQuery.ajax({
   url: {{url('/unlink-file')}},
   type:       "post",
   dataType:   "json",
   data: postData,
   success: function(data) {
    if(data.result===true){
                // File removed successfully
      
    }else{


    // Error in removing file
    }
   
   }
});

Code/function in your Controller

public function unlinkImage(Request $request){
		if($request->ajax()){
			$file_data= @parse_url($request->input('url'));
			
            $response=[];
			if($file_data['path']!=""){
				\File::delete(ltrim($file_data['path'],'/'));
				$response['result']=true;
			}else{
				$response['result']=false;
			}


			return $response;
		}
}

Code for Laravel routes

Route::post('/unlink-file', array(
   'middleware' => 'csrf',
   'as'     => 'unlink-file',
   'uses'   => 'FilesController@unlinkImage'
));

This post is submitted by one of our members. You may submit a new post here.

Related Tricks