Melodia
4 months ago
269
3
Vue

Eloquent create and axios vuejs post request does not save file and save other records with error

Posted 4 months ago by Melodia

My route looks like this:

Route::post('task/project/{project}/save', '[email protected]');

The method in the controller looks like the following:

public function createProjectTask(Request $request, Project $project) {
    $input = $request->all();
    $task = Task::create([
        'project_id' => $request->project_id,
        'owner_id' => '3',
        'name' => $request->name,
        'description' => $request->description,
        'summary' => $request->summary,
        'duration' => $request->duration,
    ]);
    if(empty($input['file'])) {
        $fileName = $request->file->getClientOriginalName();
        $request->file->move(public_path("tasks/{$task->id}"), $fileName);
        $task->fill(['file' => $fileName]);
    }
    return $task;
}

I use axios to execute the post request inside a vuex action and it looks the following from the vue side:

In the vue template, I have the function that gets the file data in case a file is selected, and then I have the submission of the form:

onFileChange(e) {
    this.task.file = e.target.files[0]
},

formSubmit(e){
    e.preventDefault()

    var formData = new FormData();
    formData.append('project_id', this.projectId)
    formData.append('name', this.task.name)
    formData.append('description', this.task.description)
    formData.append('summary', this.task.summary)
    formData.append('duration', this.task.duration)   
    
    if(this.task.file != ''){
        formData.append('file', this.task.file)
    }

    const taskData = {
        formData: formData,
        projectId: this.projectId
    }

    this.$store.dispatch('addProjectTask', taskData)

}

addProjectTask is the action and looks like the following:

addProjectTask({commit}, taskData) {
    axios.post('/task/project/' + taskData.projectId + '/save', taskData.formData)
    .then(res => {
        console.log(res.data)
        console.log("New task added")
    })
    .catch(err => console.log(err))
}

I noticed two things: 1 - the file is not saved at all. 2 - i try to save the data without an image, in the console, i get a 500 internal server error, but if i visit the database, the record actually gets added.

How can I save the records with or without image and not have the internal server error?

Please sign in or create an account to participate in this conversation.