Skip to content
Advertisement

How to upload file using laravel vue api?

i’m trying to make a form with the ability to upload files using form

i’m able to store string, int data but i’m a bit lost with the way that i need to provide for the controller and the view

this is the add template:

<template>
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h4>Add Category</h4>
            </div>
            <div class="card-body">
                <form
                    @submit.prevent="create"
                    enctype="multipart/form-data"
                >
                    <div class="row">
                        <div class="col-12 mb-2">
                            <div class="form-group">
                                <label>Title</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    v-model="category.title"
                                />
                            </div>
                        </div>
                        <div class="col-12 mb-2">
                            <div class="form-group">
                                <label>Description</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    v-model="category.description"
                                />
                            </div>
                        </div>
                        <div class="col-12 mb-2">
                            <div class="form-group">
                                <label>name</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    v-model="category.name"
                                />
                            </div>
                        </div>
                        <div class="col-12 mb-2">
                            <div class="form-group">
                                <label>path</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    v-model="category.path"
                                />
                            </div>
                        </div>
                        <div class="col-12 mb-2">
                            <div class="form-group">
                                <label>File</label>
                                <input
                                    type="file"
                                    class="form-control"
                                    v-on:change="onChange"
                                />
                            </div>
                        </div>
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary">
                                Save
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</template>

<script>
export default {
name: "add-category",
data() {
    return {
        category: {
            title: "",
            description: "",
            name: "",
            file: "",
        }
    };
},
methods: {
    async create() {
        await this.axios
            .post("/api/category", this.category)
            .then(response => {
                this.$router.push({ name: "categoryList" });
            })
            .catch(error => {
                console.log(error);
            });
    }
}
};
</script>

this is the database table:

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->text('description');
        $table->string('name')->nullable();
        $table->string('path')->nullable();  
        $table->timestamps();
    });
}

controller:

public function store(Request $request)
{
    $category = Category::create($request->post());
    return response()->json([
        'message'=>'Category Created Successfully!!',
        'category'=>$category
    ]);
}

model:

class Category extends Model
{
use HasFactory;

protected $fillable = ['title','description','name','path'];
}

app:

require('./bootstrap');
import vue from 'vue'
window.Vue = vue;

import App from './components/App.vue';
import VueRouter from 'vue-router';
import VueAxios from 'vue-axios';
import axios from 'axios';
import {routes} from './routes';

Vue.use(VueRouter);
Vue.use(VueAxios, axios);

const router = new VueRouter({
mode: 'history',
routes: routes
});

const app = new Vue({
el: '#app',
router: router,
render: h => h(App),
});

i can provide more code if necessary

the current code is working and storing in database but the only problem is uploading a file

Advertisement

Answer

Firstly you need to call onchnage function like @change="onChange($event). Secondly you need to put code in onchange function like below. onChange(event) {this.category.file = event.target.file;} And last you need to use FormData and pass Header in api in create function like below.

EDIT

methods: {
    async create() {
        var form = new FormData();
        form.append("title", this.category.title);
        form.append("description", this.category.description);
        form.append("name", this.category.name);
        form.append("file", this.category.file);
        var config = {
            header: { "Contect-type": "multipart/form-data" },
        };
        await this.axios.post("/api/category", form, config).then(response => {
            this.$router.push({ name: "categoryList" });
        }).catch(error => {
            console.log(error);
        });
    },
    onChange(event) {
       this.category.file = event.target.file;
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement