How to Image Upload Laravel 11 Vue 3 Example

Websolutionstuff | May-27-2024 | Categories : Laravel VueJs

Hello, laravel web developer! In this article, we'll see how to image upload in laravel 11 vue 3. Here, we'll learn vue 3 image upload using vite in laravel 11. Vite is a modern frontend build tool that provides an extremely fast development environment and bundles your code for production.

Also, we will use laravel breeze, inertia js, vite, and tailwind CSS to create a vue js image upload example in laravel 11.

Laravel 11 Vue 3 Image Upload

laravel 11 vue 3 image upload

 

Step 1: Install Laravel 11

In this step, we'll install the laravel 11 application using the following command.

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

 

Step 2: Create Auth with Breeze

Now, we will install Breeze using the composer command.

composer require laravel/breeze --dev

After installing Laravel Breeze, we'll create a login, and register using the vue js.

php artisan breeze:install vue

Next, we will install the node package using the following command.

npm install

Run vite using the following command.

npm run dev

Also, we will migrate the default table into the database using the following command.

php artisan migrate

 

Step 3: Create a Model and Migration

In this step, we will create migration and add fields in migration.

php artisan make:migration create_files_table

Migration:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('name');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('files');
    }
};

Run the below command and migrate the table into the database.

php artisan migrate

Now, we will create a File.php model using the following command.

php artisan make:model File

App/Models/File.php

namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
  
class File extends Model
{
    use HasFactory;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'name'
    ];
  
    /**
     * Get the user's first name.
     *
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    protected function name(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => url('uploads/'.$value),
        );
    }
}

 

Step 4: Define Routes

Now, we'll define routes in the web.php file.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileUploadController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
   
Route::get('file-upload', [FileUploadController::class, 'index'])->name('file.upload');
Route::post('file-upload', [FileUploadController::class, 'store'])->name('file.upload.store');

 

Step 5: Create Controller

Next, we'll create FileUploadController. Also, we will create an "uploads" folder in the public folder.

app/Http/Controllers/FileUploadController.php

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Validator;
use App\Models\File;
 
class FileUploadController extends Controller
{
    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function index()
    {
        $files = File::latest()->get();
        return Inertia::render('FileUpload', compact('files'));
    }
  
    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        Validator::make($request->all(), [
            'title' => ['required'],
            'file' => ['required'],
        ])->validate();
  
        $file_name = time().'.'.$request->file->extension();  
        $request->file->move(public_path('uploads'), $file_name);
    
        File::create([
            'title' => $request->title,
            'name' => $file_name
        ]);
    
        return redirect()->route('file.upload');
    }
}

 

Step 6: Create a Vue Page

In this step, we'll create a FileUpload.vue file.

resources/js/Pages/FileUpload.vue

<script setup>
import BreezeAuthenticatedLayout from '@/Layouts/Authenticated.vue';
import BreezeLabel from '@/Components/Label.vue';
import BreezeInput from '@/Components/Input.vue';
import { Head, Link, useForm } from '@inertiajs/inertia-vue3';

defineProps({
    files: Array,
});

const form = useForm({
    title: '',
    file: null
});

const submit = () => {
    form.post(route('file.upload.store'));
};

</script>

<template>
    <Head title="Dashboard" />

    <BreezeAuthenticatedLayout>
        <template #header>
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                How to Image Upload Laravel 11 Vue 3 Example - Websolutionstuff
            </h2>
        </template>

        <div class="py-12">
            <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
                <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                    <div class="p-6 bg-white border-b border-gray-200">
                        <form name="createForm" @submit.prevent="submit">
                                <div className="flex flex-col">
                                    <div className="mb-4">

                                        <BreezeLabel for="title" value="Title" />
                                        
                                        <BreezeInput 
                                            id="title" 
                                            type="text" 
                                            class="mt-1 block w-full" 
                                            v-model="form.title" 
                                            autofocus />

                                        <span className="text-red-600" v-if="form.errors.title">
                                            {{ form.errors.file }}
                                        </span>
                                    </div>

                                    <div className="mb-4">

                                        <BreezeLabel for="file" value="File" />
                                        
                                        <BreezeInput 
                                            id="file" 
                                            type="file" 
                                            class="mt-1 block w-full" 
                                            @input="form.file = $event.target.files[0]"
                                            autofocus />

                                        <span className="text-red-600" v-if="form.errors.title">
                                            {{ form.errors.file }}
                                        </span>
                                    </div>
                                </div>

                                <div v-if="form.progress" className="w-full bg-gray-200 rounded-full dark:bg-gray-700">
                                    <div className="bg-blue-600 text-xs font-medium text-blue-100 text-center p-0.5 leading-none rounded-full" :width="form.progress.percentage"> {{ form.progress.percentage }}%</div>
                                </div>
  
                                <div className="mt-4">
                                    <button
                                        type="submit"
                                        className="px-6 py-2 font-bold text-white bg-green-500 rounded"
                                    >
                                        Save
                                    </button>
                                </div>
                            </form>

                            <h1>Uploaded File List:</h1>
                            <table className="table-fixed w-full">
                                <thead>
                                    <tr className="bg-gray-100">
                                        <th className="px-4 py-2 w-20">No.</th>
                                        <th className="px-4 py-2">Title</th>
                                        <th className="px-4 py-2">Image</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="file in files">
                                        <td className="border px-4 py-2">{{ file.id }}</td>
                                        <td className="border px-4 py-2">{{ file.title }}</td>
                                        <td className="border px-4 py-2">
                                            <img :src="file.name" width="200" />
                                        </td>
                                    </tr>
                                </tbody>
                            </table>

                    </div>
                </div>
            </div>
        </div>
    </BreezeAuthenticatedLayout>
</template>

 

Step 7: Run Vue Laravel 11 Application

Now, run vue 3 image upload using vite in the laravel 11 application.

php artisan serve

Run the following command for vite.

npm run dev

To build the application run the following command.

npm run build

 


You might also like:

Recommended Post
Featured Post
How to Create Custom Login and Registration in Laravel 10
How to Create Custom Login and...

In the ever-evolving landscape of web development, crafting a tailor-made user authentication system stands as a pivotal...

Read More

Aug-25-2023

jQuery Image Magnifier on Mouse Hover
jQuery Image Magnifier on Mous...

In this article, we will see a jquery image magnifier on mouse hover. Using an image magnifier you can enlarge...

Read More

Jan-04-2021

Laravel 11 Livewire Datatable Example
Laravel 11 Livewire Datatable...

Hello, laravel web developers! In this article, we'll see how to create datatable in laravel 11 livewire using medic...

Read More

Jun-05-2024

Laravel 9 One To One Relationship Example
Laravel 9 One To One Relations...

  In this article, we will see laravel 9 one to one relationship example. Also, you can use one to one re...

Read More

Apr-01-2022