Uploading several files with Laravel and Vue JS in one go

Recently, I have been working on a project where I need to upload multiple image files using Vue JS in conjunction with Laravel on the server side.

This is the snippet from my Vue template:

<input type="file" id = "file" ref="file" v-on:change="onImageChange" multiple />

Below is the JavaScript code I've implemented:

<script>
 export default {
  data(){
    return{
      product: {},
      image: '',
    }
  },
  created() {
    let uri = `/api/product/edit/${this.$route.params.id}`;
    this.axios.get(uri).then((response) => {
        this.product = response.data;
    }); 
  },
  methods:{
    // Function to handle image changes
    onImageChange(e){
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length)
       return;
       this.createImage(files[0]);
    },
    createImage(file){
       let reader = new FileReader();
       let vm = this;
       reader.onload = (e) => {
         vm.image = e.target.result;
       };
       reader.readAsDataURL(file);
    },
    replaceByDefault(e) {
      e.target.src = this.src='/uploads/products/default_image.jpg';
    },
    saveImage(e){

        e.preventDefault()

        var file = document.getElementById('file').files;

        let formData = new FormData;
            formData.append('productId', this.product.id)
            formData.append('file', file[0])

        axios.post('/api/product/image/add', formData, {
            headers: {'Content-Type': 'multipart/form-data'}
        }).then((response) => {
            this.$router.push({name: 'view',params: { id: this.product.id }});
            });
     }

    }
   }
  </script>

I came across a resource online that mentioned looping through formData.append in Vue, but I'm unsure how to retrieve this data on the server side. Below is an excerpt from my ProductController:

$saveImage = new Gallery;
  $saveImage->product_id = $request->productId;

  $file = request()->file('file');
  $file_name = time().$file->getClientOriginalName();
  $path = $imgUpload = Image::make($file)->save(public_path('/uploads/products/' . $file_name));

  $saveImage->path = '/uploads/products/'.$file_name;
  $saveImage->status = 1;

  $saveImage->save();
  return "success";

Appreciate any guidance you can provide!

Answer №1

If you want to retrieve files in your Laravel application, you can utilize the request()->file('file') method. However, there are some adjustments required in your Vue source code if you intend to send an array of files.

Vue

let formData = new FormData;
formData.append('productId', this.product.id)
// append files
for(let i=0; i<file.length; i++){
  formData.append('file[]', file[i])
}

By using file[] instead of file, you will create an array of files in the request payload. In your Laravel backend, you can then retrieve this array by using request()->file('file'). If you only need a specific file from the array (e.g., the first one), you can access it with request()->file('file.0').

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the power of HTML5, store data locally on

I am curious about the possibility of using local storage on a different page. I want to track clicks made on one page and display it on another, but I'm not sure how to go about it or if it's even feasible. Any help you can provide would be grea ...

What are the specific circumstances in which the onerror and ontimeout properties are utilized? (regarding

When utilizing the XMLHttpRequest class to send payload data from a web client to a web server, I encounter some common errors that need to be handled... REQUEST TIMEOUT (CONNECTION TIMEOUT) 500, INTERNAL SERVER ERROR 502, BAD GATEWAY 503, SERVICE UNAVAI ...

Exploring Object Arrays with Underscore.js

Here is an array of objects that I am working with: var items = [ { id: 1, name: "Item 1", categories: [ { id: 1, name: "Item 1 - Category 1" }, { ...

Double array summation function

It is necessary for me to calculate the total coursePrice from this JSON data source here using AngularJS (javascript). I need to calculate two sums: one for each school and another for all schools combined. I have already displayed all the data in a tabl ...

Enhancing the Performance of jQuery Scripts

My jQuery function called textfill is utilized on numerous div elements. Essentially, it resizes the text inside each div to perfectly fit the container so that longer texts are made smaller than shorter ones while maintaining the maximum font size without ...

Utilizing AngularJS with multiple dynamically generated forms on a webpage: Extracting data from each form

I am facing a challenge with a web page I have created that uses PHP to generate forms for updating information via a REST API on a remote server. The structure of the forms is as follows: Textfield: name textfield: description select: type (ng-model="se ...

Merging a prop of array type in a Vue component

I'm encountering an issue in my component where using the splice function on an array prop does not trigger the $emit event. Can anyone provide some insight into why this might be happening? The removeItem method is called by clicking a button. View ...

An error occurred while trying to load the resource in the Redux-Saga: connection refused

Utilizing axios allows me to make calls to the backend server, while redux-saga helps in managing side effects from the server seamlessly. import {call, put, takeEvery} from "redux-saga/effects"; import {REQUEST_FAILED, REQUEST_SUCCESS, ROOT_URL, SUBMIT_U ...

Unresolved promise rejection on Repl.it

I decided to add a basic leaderboard feature to my game on Repl.it, so I set up a node.js backend for it. Here's the code snippet for the backend: const express = require('express'); const Client = require('@replit/database'); cons ...

Adjust the primary scrolling section of a webpage to halt once it reaches a specific distance from the bottom of the viewport

I am facing a situation where I need to ensure that when scrolling down, a fixed pink menu bar at the bottom of the page does not overlap with the main blue content. This can be achieved by treating the blue content as an iframe positioned 60px from the bo ...

Is it possible to compile or render a component by using the text within interpolation handlebars in a forceful manner?

I have come across a third-party Vue component that allows me to set the title of a group of HTML elements, with the text being rendered inside a legend tag. My understanding is that Vue interpolation text is limited in what it can do. Now I am curious i ...

Steps for including a subdocument within a mongoose schema

I am currently working on setting up a subdocument within a mongoose schema using node.js/Express. There are two schemas in play: Member and Address Member.js // app/models/member.js // Loading mongoose to define the model var mongoose = require(' ...

There appears to be an issue with the functionality of the Bootstrap toggle tab

Currently, I am facing a toggle issue and having trouble pinpointing the root cause as there are no errors appearing in the console. The problem involves two tabs that can be toggled between - "pay" and "method". Initially, the default tab displayed is "pa ...

Only a single element in the array is being pushed by the JavaScript code, not all elements

Having an issue with my script where it is only returning one element out of a class that has 10 elements. Can anyone help me pinpoint the problem? `function() { var vins = document.querySelectorAll('.dws-vehicle-listing-item-field.dws-vehicle-field- ...

Acquiring JSON data from Node.js within Angular

After searching everywhere, I finally managed to retrieve all the data from my database using node and saved it into a file. The data is simple JSON chat logs that can be accessed through my browser with ease. Here's a snippet of how it looks: [{ " ...

I am in need of a efficient loader for a slow-loading page on my website. Any recommendations on where to find one that works

I'm experiencing slow loading times on my website and I'm looking to implement a loader that will hide the page until all elements are fully loaded. I've tested several loaders, but they all seem to briefly display the page before the loader ...

Ways to modify the prop of useSlot() in Vue 3

I have a query about how to access the props change retrieved from useSlots() This is a file that defines the Parent component with the Child component as the Parent component's slot. I have also passed some props to the Child component. <script s ...

Replace all occurrences of $regex in Node.js with the json data format

Here is a JSON example var json= { name: { '$regex': /^Amer$/i }, 'countries.name': { '$regex': /^UNited states$/i } } I am looking to reformat it using either lodash or string/json replace method to achieve the following st ...

Combine Immer and NgRx reducer for improved state management

Upon analyzing redux and ngrx, it appears that immer is the preferred library for creating a copy of the state before storing it. In following the example provided by immer, I implemented the following code in my reducer: on(exampleActions.updateExample ...

Encountering Issues with Discord JS as Member Fetch Returns Undefined

I'm facing an issue with fetching specific server members by their user id in order to assign a role to them. I keep getting an undefined response each time. Even though this bot has administrator permission and all required intents are assigned, I a ...