DEV Community

Cover image for File Upload in Laravel and Vue.js
Engineer Robin 🎭
Engineer Robin 🎭

Posted on

1 1 1 1 1

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.

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

Image of DataStax

AI Agents Made Easy with Langflow

Connect models, vector stores, memory and other AI building blocks with the click of a button to build and deploy AI-powered agents.

Get started for free

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay