Search code examples
javascriptlaravelvue.jsform-data

Laravel save image from formdata


I am trying to save image sent from my javascript (using vue) as a formdata, I am trying to save it properly to my database and create a folder inside my storage directory.

So far I did following:

// the axios works properly
submit () {
    const formData = new FormData();
    formData.append('thumbnail', this.selectedImageFile);
    formData.append('title', this.title)
    formData.append('image', this.image)
    formData.append('thumbnail', this.thumbnail)
    formData.append('day', this.day)

    if (this.$refs.form.validate()) {
        axios.post('/event/store', formData)
        .then((response) => {
            console.log("event saved: " + response.data);
        })
        .catch((error) => {
            console.log("error trying to save event: " + response);
        })
    }
},

In my controller's store method I do following:

public function store(EventRequest $request)
{
    $event = $this->event->create([
        'title' => $request->title,
        'image' => $request->image,
        'thumbnail' => $request->thumbnail
    ]);

    $this->event->createDir($request->file('image'), $request->file('thumbnail'), $request->title);

    if($event) {
        return response()->json('success');
    }            

    return response()->json('An error accured');
}

The createDir method in create in my Repository

public function createDir($image, $thumbnail, $title)
{
    $image->store($title.'/image');
    $thumbnail->store($title.'/thumbnail');
}

The Axios post works. $request->file('image') and $request->file('thumbnail') return null whereas if I output the formdata in my console I get a proper log.

I would like to save the filename in my database and create a folder inside storage with both images.

I am not sure how to manage this with FormData.


Solution

  • Simply update your store method to following:

    public function store(EventRequest $request)
    {
        $event = $this->event->create([
            'title' => $request->title,
            'image' => $request->image,
            'thumbnail' => $request->thumbnail
        ]);
    
        $request->file('image')->store($request->title.'/image');
        $request->file('thumbnail')->store($request->title.'/thumbnail');
    
        if($event) {
            return response()->json('success');
        }            
    
        return response()->json('An error accured');
    }
    

    This will request to files from your FormData and store them inside your storage folder and add a random hashed name. So this:

        $request->file('image')->store($request->title.'/image');
        $request->file('thumbnail')->store($request->title.'/thumbnail');
    

    Moves the images for instance to this location:

    storage/app/dragon/thumbnail/abcaksdhsadui123.png // your request title is in this example dragon
    storage/app/dragon/image/abcaksdhsadui123.png