nscott's avatar

Livewire file upload changes the file name in the database

I am using Livewire to handle my file uploads, but I have it set up to leave the file name as the original that the client will be using. However, when the file is saved into the Database it always adds the word product/ to the beginning of the name but the actual file that is loaded into the folder is just the file name so the image does not render on the frontend. Here is my code for storing the image:

protected $rules = [
        'product_image'=> 'required | image',
        'altTag' => 'required|max:255',
    ];

    private function resetForm() {
            $this->product_image = '';
            $this->altTag = '';
    }

    public function store() {
        
        $this->validate();

        $filename = $this->product_image->getClientOriginalName();

        ProductImage::create([
            'product_image' => $this->product_image->storeAs('product', $filename),
            'image_alt_tag' => $this->altTag,
            'image_title' => Str::replace('.jpg', '', $filename),
            'product_id' => $product_id,
        ]);

        $this->resetForm();
    }

So if I upload a file for example called test.jpg, in the Database the name becomes product/test.jpg but in the file directory, it stays as test.jpg. I tried to remove it with Str::replace but that did not work either.

0 likes
5 replies
tykus's avatar
tykus
Best Answer
Level 104
$filename = $this->product_image->getClientOriginalName();
$this->product_image->storeAs('product', $filename);
ProductImage::create([
    'product_image' => $filename,
    // ...
nscott's avatar

@tykus thanks. Didn’t realize I had to store it first and then call the create method. I was following along in the docs and that wasn’t mentioned. And couldn’t find that anywhere.

tykus's avatar

@nscott you don't have to... just the return from storeAs is the path (incl. products/)

Snapey's avatar

product/ is what is known as a folder

you asked laravel to store the file in a folder called product and to return to you the path

Please or to participate in this conversation.