Newbie
Newbie

Reputation: 1079

Laravel 4.x: How to delete a file?

I've got an table name's image.It has id,name,url and timestamp field.

here is my code:

$image=Image::find($id);
$url=$image->url;
if(unlink("$url")){
    $image->delete();
    return true;
}else
    return false;

It doesn't work so I echo the url i've got:

http://localhost/project/public/uploads/gallery/1/_DSC845645490.jpg

But when i check it:

if(file_exists(Image::find($id)->url)){
            return 'has image';
        }else{
            return 'no image';
        }

I've got 'no image' althought I can show that Image on web browser

Why is that???Can anybody help me?

Upvotes: 0

Views: 1473

Answers (2)

Mohammed Samiullah
Mohammed Samiullah

Reputation: 175

I used this and it worked everytime i used

File::delete(public_path('img/slider/').$delete_image);

here $delete_image is name of the file and path written in public_path() method is the path which begins from root folder of laravel yourProject/public/

Upvotes: 1

Peter
Peter

Reputation: 188

There's method in class Illuminate\Filesystem\Filesystem (See http://laravel.com/api/4.1/ and search for 'filesystem').

You can call its method delete like this

File::delete(path/to/file/relative/to/public/folder);

BTW: Maybe even your code is good but what do you have in url field? If it's relative paht, you have to also prepend it with something like

<?php 
  if( file_exists( $_SERVER{'DOCUMENT_ROOT'} . "/my_images/abc.jpg"))  { 
    ... 
  } 
?> 

(Example from http://www.php.net/manual/en/function.file-exists.php)

Upvotes: 0

Related Questions