In this tutorial you will learn about the Laravel 8 Vue JS File Upload Tutorial With Example and its application with practical example.
In this Laravel 8 Vue JS File Upload Tutorial With Example, we will learn how to upload a file in Laravel 8 Vue JS application with example. I’ll guide you through step by step how to upload files with Vue js using Axios post request In Laravel 8 Vue JS application. In this tutorial, we will be creating a simple form to send form data (files, images, input fields etc) with Vue js using Axios to send POST request in laravel.
Laravel 8 Vue JS File Upload Tutorial With Example
In this step by step tutorial I will demonstrate you how to upload a file in Laravel 8 Vue JS application. Please follow the instruction given below:
- Step 1: Install Laravel 8
- Step 2: Setup Database Credentials
- Step 3: Create Model And Migration
- Step 4: NPM Configuration
- Step 5: Add Routes
- Step 6: Create Controller By Command
- Step 7: Create Vue Component
- Step 8: Register Vue App
- Step 9: Run Development Server
Step 1: Install Laravel 8
First of all we need to create a fresh laravel project, download and install Laravel 8 using the below command
1 |
composer create-project --prefer-dist laravel/laravel larablog |
Make sure you have composer installed.
Step 2: Setup Database Credentials
Now, lets create a MySQL database and connect it with laravel 8 application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your database name here DB_USERNAME=database username here DB_PASSWORD=database password here |
Step 3: Create Model And Migration
Now, we have to define table schema for photo table. Open terminal and let’s run the following command to generate a Photo model along with a migration file to create photo table in our database.
1 |
php artisan make:model Photo -m |
Once this command is executed you will find a migration file created under “database/migrations”. Lets open migration file created and put following code in it –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePhotosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('photos', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('photos'); } } |
Next, migrate the table using the below command:
1 |
php artisan migrate |
After, the migration executed successfully the photo table will be created in database.
Step 4: NPM Configuration
Now, you need to setup Vue Js In Laravel 8 and install Vue Js dependencies using NPM. So execute the following command on command prompt.
1 |
php artisan preset vue |
Use below command to Install all Vue Js dependencies:
1 |
npm install |
Step 5: Add Routes
Now, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 5 6 |
Route::get('upload_file', function () { return view('upload'); }); use App\Http\Controllers\FileUploadController; Route::post('store_file', [FileUploadController::class, 'fileStore']); |
Step 6: Create Laravel Controller Using Artisan Command
Next, we have to create a controller to handle file upload operation. Lets Create a controller named FileUploadController using command given below –
1 |
php artisan make:controller FileUploadController |
Once the above command executed, it will create a controller file FileUploadController.php in app/Http/Controllers directory. Open the FileUploadController.php file and put the following code in it.
app/Http/Controllers/FileUploadController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; Use App\Models\Photo; class FileUploadController extends Controller { // function to upload file in 'upload' folder public function fileStore(Request $request) { $upload_path = public_path('upload'); $file_name = $request->file->getClientOriginalName(); $generated_new_name = time() . '.' . $request->file->getClientOriginalExtension(); $request->file->move($upload_path, $generated_new_name); $insert['title'] = $file_name; $check = Photo::insertGetId($insert); return response()->json(['success' => 'You have successfully uploaded "' . $file_name . '"']); } } |
Step 7: Create Vue Component In Laravel Application
Now we will create a Vue Component, go to resources/assets/js/components folder and create a filed called FileUpload.vue. Put the following code into your FileUpload.vue components file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
<template> <div class="container" style="margin-top: 50px;"> <div class="text-center"> <h4>File Upload with VueJS and Laravel</h4><br> <div style="max-width: 500px; margin: 0 auto;"> <div v-if="success !== ''" class="alert alert-success" role="alert"> {{success}} </div> <form @submit="submitForm" enctype="multipart/form-data"> <div class="input-group"> <div class="custom-file"> <input type="file" name="filename" class="custom-file-input" id="inputFileUpload" v-on:change="onFileChange"> <label class="custom-file-label" for="inputFileUpload">Choose file</label> </div> <div class="input-group-append"> <input type="submit" class="btn btn-primary" value="Upload"> </div> </div> <br> <p class="text-danger font-weight-bold">{{filename}}</p> </form> </div> </div> </div> </template> <script> export default { mounted() { console.log('Component successfully mounted.') }, data() { return { filename: '', file: '', success: '' }; }, methods: { onFileChange(e) { //console.log(e.target.files[0]); this.filename = "Selected File: " + e.target.files[0].name; this.file = e.target.files[0]; }, submitForm(e) { e.preventDefault(); let currentObj = this; const config = { headers: { 'content-type': 'multipart/form-data', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content, } } // form data let formData = new FormData(); formData.append('file', this.file); // send upload request axios.post('/store_file', formData, config) .then(function (response) { currentObj.success = response.data.success; currentObj.filename = ""; }) .catch(function (error) { currentObj.output = error; }); } } } </script> |
Now open resources/assets/js/app.js and include the FileUpload.vue component in it.
resources/assets/js/app.js
1 2 3 4 5 6 |
require('./bootstrap'); window.Vue = require('vue'); Vue.component('file-upload-component', require('./components/FileUpload.vue').default); const app = new Vue({ el: '#app', }); |
Step 8: Register Vue App
Now, we will create a blade view file to define Vue app. Go to resources/views
folder and make a file named upload.blade.php. Then put the following code into upload.blade.php as following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="csrf-token" content="{{ csrf_token() }}"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <title>File Upload with VueJS and Laravel - tutsmake.com</title> <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css"> </head> <body> <div id="app"> <file-upload-component></file-upload-component> </div> <script src="{{asset('js/app.js')}}"></script> </body> </html> |
Step 9: Start Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 2 3 |
npm run dev or npm run watch |