1

In my Laravel 7 project, I am renaming images on the upload based on the Station name field. Converting a string to slug using Str::of($name)->slug() see below

Naming the image

public function setStationName($extension, $name)
{
    return 'station-' . Str::of($name)->slug() . '.' . $extension;
}

So it will generate a name like station-foo-bar.png and finally storing this name to the photo column to database.

Since the name field is editable so the user will be able to change the name field at any time and if the user is uploading a new image with the name field modified, the new image will have a new name.

Here I am getting trouble.

While updating the record with new image and modified field, if I delete the older image using the getOriginal('photo) method, it is not deleting the image. However, it deletes the image if the name field isn't modified.

Station Model

public function deletePhoto()
{
    Storage::disk('public')->delete($this->stationPhotoDir . '/' . $this->getOriginal('photo'));
}

When I dd to check the value of getOriginal('photo') it is returning the correct filename that I want to delete but it is not deleting.

Question:

How to delete old images using the getOriginal() method?

3
  • did you call the getOriginal before saving in the database ? can you show us where did you call deletePhoto ? Commented Apr 16, 2020 at 11:10
  • @Maraboc yes I am doing that right before any other code in update method. It is on the very first line. Commented Apr 16, 2020 at 14:33
  • @Maraboc Oh my bad. Very stupid mistake. By looking in the folder I found it is deleting the image. However, I have more sizes that I have to delete separately and here I misunderstood and overlooked. This means there is no issue with getOriginal but my stupid misunderstanding. Therefore the question doesn't deserve to be here. Thanks a lot. Commented Apr 16, 2020 at 14:36

1 Answer 1

0

Your problem isn't getOriginal, it's the path that is incorrect in the delete operation.

Add Log::info($this->stationPhotoDir . '/' . $this->getOriginal('photo')) and see what the path says.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.