Code to remove a file from url in Laravel 5.4 via ajax

By using below code snippet , you can easily remove a file from disk or storage in Laravel 5.4.

function to unlink a file in laravel 5.4.jpg
function to unlink a file in laravel 5.4.jpg

Ajax code

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

    // Error in removing file
    }
   

   }

});

In Laravel 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;
		}

	}

In Routes

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

Thank you!!

Leave a Reply

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