Attempting to save an image captured in a Vue form and then transmit it to the Laravel backend

Hey everyone, I'm a newcomer to Vue and Laravel and I'm currently working on a REST project. I have a form that allows users to upload an image, but I keep encountering an error when trying to store it in the database:

"Request failed with status code 422" and "The image must be an image"

I'm struggling to find a solution for this issue. Any suggestions or tips would be greatly appreciated!

<script>
export default {
    data() {
        return {
            title: undefined,
            year: undefined,
            director: undefined,
            plot: undefined,
            rating: undefined,
            image: null,
        };
    },
    methods: {
        insertedFile(e) {
            this.image = e.target.files[0];

        },
        addFilm() {

            const formData = new FormData;
            formData.set('image', this.image)
            console.log(formData.get('image'));
            // 
            axios
                .post("/api/films", {
                    title: this.title,
                    year: this.year,
                    director: this.director,
                    plot: this.plot,
                    rating: this.rating,
                    image:formData
                })
                .then((response) => {
                   console.warn(response)
                });
        },
    },
};
</script>

<template>
    <form @submit.prevent="addFilm()" enctype="multipart/form-data" method="post">
        <input type="text" name="title" placeholder="title" v-model="title" />
        <input type="number" name="year" placeholder="year" v-model="year" />
        <input
            type="text"
            name="director"
            placeholder="director"
            v-model="director"
        />
        <input type="text" name="plot" placeholder="plot" v-model="plot" />

        <input
            type="number"
            name="rating"
            placeholder="rating"
            v-model="rating"
        />
        <input
            type="file"
            name="image"
            id="image"
            @change="insertedFile($event)"
        />
        <button type="submit">Submit</button>
    </form>
</template>

Controller:

public function store(Request $request)
    {

        $request->validate([

            'title' => 'required',
            'year' => 'required',
            'plot' => 'required',
            'director' => 'required',
            'rating' => 'required',
            'image' => 'image|mimes:jpg,png,jpeg,svg|max:2048'

        ]);
    


            $film = new Film([
                'title' => $request->title,
                'year' => $request->year,
                'plot' => $request->plot,
                'director' => $request->director,
                'rating' => $request->rating,
                "image" => $request->file('image')->store('images', 'public')

            ]);
            $film->save();
       

        return redirect()->route('home')
            ->with('success', 'film created successfully!');
    }

Answer №1

If you want to send a payload (data) along with your formData, make sure to merge them together and update the content-type header in your axios request to multipart/form-data:

const configuration = {
    headers: {
        'content-type': 'multipart/form-data'
    }
}

let formData = new FormData();
formData.append('title', this.title);
formData.append('year', this.year);
formData.append('director', this.director);
formData.append('plot', this.plot);
formData.append('rating', this.rating);
formData.append('image', this.image);

axios.post('api/movies', formData, configuration)
.then((response) => {
    console.log(response);
})
.catch((error) => {
    console.error(error);
});

Answer №2

When passing the FormData object as an image to axios, it is important to ensure that all the necessary data is included within the object.

The addFilm method should be structured in the following way:

            const data = new FormData;

            data.append('image', this.image)
            data.append('title', this.title)
            data.append('year', this.year)
            data.append('director', this.director)
            data.append('plot', this.plot)
            data.append('rating', this.rating)
            data.append('image', this.image)

            axios
                .post("/api/films", data)
                .then((response) => {
                   console.log(response)
                });

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

What are the best practices for effectively managing jQuery UI sliders?

I am currently developing a web application that involves updating jQuery UI sliders using JavaScript. While I have managed to resolve most of the issues related to updating the slider after initialization, there is one particular issue that remains unreso ...

How can I utilize data retrieved from $http.get in Vue.js once the page has finished loading?

I'm having trouble figuring out how to trigger a function in Vue.js after an $http.get request has completed. In the example below, I want to automatically select an element of foobar right after the page loads, but it only works when there's an ...

jQuery fails to locate class following AJAX reply

In my application, there is a cart feature where users can remove items from their cart, triggering a refresh of the contents using AJAX. However, I noticed that after removing an item from the cart, the response switches from asynchronous to synchronous m ...

How to build custom middleware with parameters in Node.js

I'm working on creating a middleware in nodejs for access levels, and I've written the following middleware: class AccessUser extends middlware { async AccessUser(access,req, res, next) { const getTokenFrom = (req) => { const autho ...

Exploring the Ins and Outs of Transition Testing in D3 v4

Previously, in older versions of D3, you were able to create unit tests that checked the state of a D3 component after all transitions had finished by flushing the timer with d3.timer.flush(). However, in D3 version 4, this has changed to d3.timerFlush(), ...

Issue encountered while attempting to save file to designated location: to://app.js during Laravel 9 composer update on the staging site

After running a composer updater on a staging site for an app I'm working on, I encountered an error when Composer generated its package manifest: > @php artisan vendor:publish --tag=laravel-assets --ansi --force League\Flysystem\Unab ...

What is the process for changing proxy settings through the command line when using Create React App?

I recently created a React project using Create React App and set up the development server to proxy API requests through the proxy setting in my package.json: ... "proxy": "https://dev-backend.example.com" ... However, I am looking ...

Unlock the Power of Rendering MUI Components in ReactJS Using a For Loop

Hey there! Hope everything is going well. I've been working on a fun project creating an Advent/Chocolate Box Calendar using ReactJS. One challenge I'm facing is figuring out how to iterate over a for loop for each day in December and render it ...

At what point are DOMs erased from memory?

Recently, I've been working on an application that involves continuous creation and removal of DOM elements. One thing I noticed is that the process memory for the browser tab keeps increasing even though the javascript heap memory remains steady. To ...

Utilizing the Vue Component Scope with External JavaScript

Is it possible to access Vue component data properties and methods from external JavaScript? I am working on creating a hybrid application where part of the screen is a Vue component. I would like to be able to call a method inside that component when a bu ...

The auto-refresh feature of DataTables is not functioning as expected

Having trouble with the reload feature of DataTables. This is the code I'm using to load and reload the table on the server-side: $( document ).ready(function() { $('#dienst_tabelle').DataTable( { "ajax": "getData ...

Have the quotes within my markup been replaced with HTML entities?

Currently, I am working on a content page that uses a master page which includes a text box and a button. My goal is to have the button execute some JavaScript code before performing any other actions. At the moment, I am in the testing phase of this JavaS ...

Using JavaScript to parse JSON response for sending status data through a POST request

I have successfully implemented a PHP code for file uploads. However, I am facing an issue retrieving the JSON response that indicates the upload status. Upon uploading a file via POST method, the response appears as follows: {"html_content":"<p>Fi ...

Struggling to make jQuery code function in an external file without causing clashes with additional jQuery code

When incorporating this simple code into its own separate file, I encounter some jQuery conflicts with another piece of code. jQuery(function ($) { $(".tabContents").hide(); $(".tabContents:first").show(); $("#tabContainer ul li a").click(fun ...

Exploring the integration of Sphinx with Laravel 4

As a beginner in the world of Sphinx, I am looking for a query that can help me search specific keywords across all database tables using Php Sphinx Mysql. I have integrated the Sphinx server into my Laravel framework. If anyone has any suggestions, plea ...

The React date picker has limitations, as there are certain dates that users are unable

Recently, I came across an issue with a react date picker that I am using. Here is the code snippet: <DatePicker selected={selectedDate} onChange={handleDateChange} minDate={new Date()} className="form-control" /> In this image, when ...

Divide a list Observable into two parts

In my code, I have an Observable called 'allItems$' which fetches an array of Items. The Items[] array looks something like this: [false, false, true, false] My goal is to split the 'allItems$' Observable into two separate Observables ...

Recursive array generation

Given an array 'featureList', the goal is to create a new array 'newArray' based on a specific ID. For example, for ID 5, the newArray would be ['MotherBoard','Antenna','Receiver'], where Receiver correspon ...

Limit input to numbers only in Semantic UI React Form Field

I've developed a custom CurrencyInput React component for users to input numeric values. I set the input type to "number", but unfortunately, this only seems to function properly in Chrome (as Firefox still allows non-numeric entries). Here is the co ...

What is the proper way to utilize mixins from .scss files within .vue files?

Encountered an issue with the error message "no mixin named sm" when attempting to utilize my SCSS mixins in Individual Vue Components, where 'sm' is the name of my mixin variable. The file _mixins.scss is located within the assets/styles folder ...