G
G
Gevorg11222020-02-25 19:01:54
Laravel
Gevorg1122, 2020-02-25 19:01:54

How to delete a file in laravel?

The file path in the database is stored in this form -

/storage/img/COwpwZLq3PeFO3TdxK4EVXQ8EGo77vATZZEi8VHC.jpeg
and for her
Storage::delete('/storage/img/COwpwZLq3PeFO3TdxK4EVXQ8EGo77vATZZEi8VHC.jpeg')
does not work, in delete you need to specify the path of this format
public/img/COwpwZLq3PeFO3TdxK4EVXQ8EGo77vATZZEi8VHC.jpeg

How to solve the problem?
Is there a way to store only the filename in the database and not the entire path?

Controller:
$path = Storage::putFile('public/img', $request->file('img'));
$url = Storage::url($path);
$post->img = $url;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Talalaev, 2020-02-26
@Gevorg1122

Reading the documentation and learning good practice makes life a little easier.
So.
Storing url in the database, as you do, is usually not profitable and uninteresting. This is necessary in exceptional cases of a one-time mini-project, when you know for sure the settings will not change and the files will not be edited. Or, in specialized databases for caching the result of url generation.
In other cases, you need to store the file name in the database. Ideally, split the file name, but in most cases two fields will suffice: name with path + drive name. This will close most cases for future scaling. But if you're really too lazy, then the drive name can also be omitted, although I advise you to add this field.
Next, your code:

$path = Storage::putFile('public/img', $request->file('img'));
$url = Storage::url($path);
$post->img = $url;

We change it to a simpler one (although you can make an analogue from yours, of course, by removing the line from $url and saving $path to the model)
// file('img') - это имя файла(инпута формы например) из запроса
// store('img') - это имя подпапки для
// 'public' - Диск из настроек (см filesystems.php)
$path = $request->file('img')->store('img', 'public');
$post->img = $path;

Now it's easy to remove. do not forget that we are working with files (by default), relative to the folder /storage/app/(I put a slash at the beginning to show that the path is from the root of the folder with the project)
Therefore, when you pass a pre-generated url to the delete method. it won't find anything and it won't delete anything.
But now we store just the relative path of the file.
Storage::delete($post->img);
Now it will work, do not forget to clear the field after deletion, if you do not delete the post itself.
Further, we get the url itself like this
$url = asset($post->img);
Well, or if you do it right away in blade templates Well, of course, I omitted all sorts of checks and so on for simplicity
<img src="{{asset($post->img)}}">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question