Single Image Upload Example using VueJS & Laravel

Single Image Upload Example using VueJS & Laravel

Single Image Upload Using Vue.js & Laravel

Uploading images is a common requirement in modern web applications. In this guide, we’ll build a simple image upload feature using Vue.js as the front end and Laravel as the back end.

1. Set Up Laravel Backend

First, create a new Laravel project if you haven’t already:

composer create-project laravel/laravel image-upload cd image-upload

Install Laravel CORS & Storage Link

Enable CORS to allow Vue.js to interact with Laravel:

composer require fruitcake/laravel-cors php artisan storage:link

Create a Migration for Image Uploads

Run the following command to create an images table:

php artisan make:migration create_images_table

Modify the migration file in database/migrations/xxxx_xx_xx_xxxxxx_create_images_table.php:

public function up() { Schema::create('images', function (Blueprint $table) { $table->id(); $table->string('file_path'); $table->timestamps(); }); }

Run the migration:

php artisan migrate

2. Build the Image Upload API in Laravel

Create a Controller

php artisan make:controller ImageUploadController

Modify app/Http/Controllers/ImageUploadController.php:

namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Image; class ImageUploadController extends Controller { public function upload(Request $request) { $request->validate([ 'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', ]); if ($request->hasFile('image')) { $file = $request->file('image'); $path = $file->store('uploads', 'public'); $image = Image::create(['file_path' => $path]); return response()->json(['message' => 'Image uploaded successfully!', 'path' => asset('storage/' . $path)]); } return response()->json(['message' => 'Upload failed'], 400); } }

Set Up Routes in Laravel

Modify routes/api.php:

use App\Http\Controllers\ImageUploadController; Route::post('/upload', [ImageUploadController::class, 'upload']);

3. Set Up Vue.js Frontend

Install Vue in Laravel

Inside your Laravel project, install Vue and dependencies:

npm install vue@3 axios

Create a Vue Component for Image Upload

Inside resources/js/components/ImageUpload.vue:

<template> <div class="upload-container"> <h2>Upload an Image</h2> <input type="file" @change="handleFileUpload" /> <button @click="uploadImage">Upload</button> <p v-if="message">{{ message }}</p> <img v-if="imageUrl" :src="imageUrl" class="preview" /> </div> </template> <script> import axios from "axios"; export default { data() { return { file: null, message: "", imageUrl: "", }; }, methods: { handleFileUpload(event) { this.file = event.target.files[0]; }, async uploadImage() { if (!this.file) { this.message = "Please select an image."; return; } let formData = new FormData(); formData.append("image", this.file); try { let response = await axios.post("http://127.0.0.1:8000/api/upload", formData, { headers: { "Content-Type": "multipart/form-data", }, }); this.message = response.data.message; this.imageUrl = response.data.path; } catch (error) { this.message = "Upload failed. Please try again."; } }, }, }; </script> <style> .upload-container { text-align: center; margin-top: 20px; } .preview { width: 200px; margin-top: 10px; } </style>

4. Register Vue Component in Laravel

Modify resources/js/app.js:

import { createApp } from "vue"; import ImageUpload from "./components/ImageUpload.vue"; const app = createApp({}); app.component("image-upload", ImageUpload); app.mount("#app");

5. Add Vue Component to Laravel Blade File

Modify resources/views/welcome.blade.php:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue Image Upload</title> @vite('resources/js/app.js') </head> <body> <div id="app"> <image-upload></image-upload> </div> </body> </html>

6. Start the Laravel & Vue Application

Run Laravel backend:

php artisan serve

Run Vue frontend:

npm run dev

7. Test the Image Upload Functionality

  • Open http://127.0.0.1:8000 in your browser.
  • Select an image and click Upload.
  • You should see the uploaded image preview and success message.

Conclusion 

✅ Laravel handles file storage securely.
✅ Vue.js provides a smooth frontend experience.
✅ Axios helps communicate between Vue & Laravel.

Now you have a fully functional image upload feature using Vue.js & Laravel! 🚀 Let me know if you need any modifications. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close