DEV Community

Cover image for File Upload in Laravel and Vue.js
RobinIVI
RobinIVI

Posted on

File Upload in Laravel and Vue.js

Uploading files is a common feature in web applications. In this guide, we will walk through implementing file upload functionality using Laravel (Backend) and Vue.js (Frontend). Laravel will handle the server-side file storage, while Vue.js will provide a smooth client-side experience.

Prerequisites

  • Basic knowledge of Laravel and Vue.js.
  • Laravel installed (composer create-project laravel/laravel myapp).
  • Vue.js integrated with Laravel.
  • Axios for handling HTTP requests.

Step 1: Setting Up Laravel Backend

Install Laravel

If you haven't already installed Laravel, use:

composer create-project laravel/laravel myapp
Enter fullscreen mode Exit fullscreen mode

Move into the project directory:

cd myapp

Enter fullscreen mode Exit fullscreen mode

Create File Upload Controller

Run the following command to generate a new controller:

php artisan make:controller FileUploadController
Enter fullscreen mode Exit fullscreen mode

Open app/Http/Controllers/FileUploadController.php and modify it as follows:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FileUploadController extends Controller
{
    public function upload(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:jpg,jpeg,png,pdf|max:2048'
        ]);

        if ($request->hasFile('file')) {
            $path = $request->file('file')->store('uploads', 'public');
            return response()->json(['message' => 'File uploaded successfully', 'path' => $path]);
        }

        return response()->json(['error' => 'No file uploaded'], 400);
    }
}
Enter fullscreen mode Exit fullscreen mode

Define API Route

Open routes/api.php and add:

use App\Http\Controllers\FileUploadController;

Route::post('/upload', [FileUploadController::class, 'upload']);
Enter fullscreen mode Exit fullscreen mode

Configure Storage

Run the following command to create a symbolic link for public access:

php artisan storage:link
Enter fullscreen mode Exit fullscreen mode

Step 2: Setting Up Vue.js Frontend

Install Vue and Dependencies

Inside the Laravel project, install Vue.js:

npm install vue axios
Enter fullscreen mode Exit fullscreen mode

Create File Upload Component

Inside resources/js/components/UploadComponent.vue, add:

<template>
    <div>
        <input type="file" @change="handleFileUpload" />
        <button @click="submitFile">Upload</button>
    </div>
</template>

<script>
import axios from 'axios';
export default {
    data() {
        return {
            file: null
        };
    },
    methods: {
        handleFileUpload(event) {
            this.file = event.target.files[0];
        },
        async submitFile() {
            let formData = new FormData();
            formData.append('file', this.file);

            try {
                const response = await axios.post('/api/upload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
                alert(response.data.message);
            } catch (error) {
                alert('File upload failed');
            }
        }
    }
};
</script>
Enter fullscreen mode Exit fullscreen mode

Register Component in Vue App

Modify resources/js/app.js to include the component:

import { createApp } from 'vue';
import UploadComponent from './components/UploadComponent.vue';

const app = createApp({});
app.component('upload-component', UploadComponent);
app.mount('#app');
Enter fullscreen mode Exit fullscreen mode

Compile Assets

Run:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Step 3: Testing the File Upload

  • Start the Laravel backend:
php artisan serve
Enter fullscreen mode Exit fullscreen mode
  • Open your Laravel frontend in the browser where Vue is integrated.
  • Use the file input to select a file and click upload.
  • The file should be stored in storage/app/public/uploads.

Top comments (0)