React JS Image Upload using Vite in Laravel 9 Example

Today we are going to learn creating React JS Image Upload using Vite in Laravel 9 Example. This tutorial will cover how to upload image using vite in laravel 9 application.

React JS is a free and open-source front-end JavaScript library for building user interfaces based on UI components. It is maintained by Meta and a community of individual developers and companies.

Vite is a modern frontend build tool that provides an extremely fast development environment and bundles your code for production. When building applications with Laravel, you will typically use Vite to bundle your application’s CSS and JavaScript files into production ready assets.

Steps for React JS Image Upload using Vite in Laravel 9 Example:

  • Step 1: Installing fresh new Laravel 9 Application
  • Step 2: Creating Database
  • Step 3: Creating Auth with Breeze
  • Step 4: Creating Migration and Model
  • Step 5: Creating Route
  • Step 6: Creating Controller
  • Step 7: Creating React Pages
  • Step 8: Testing
  • Step 9: Conclusion

Also Read: Create Custom Artisan Command Laravel 9 Example

Step 1: Installing fresh new Laravel 9 Application

First step we are going to install a fresh new laravel 9 application. To install a laravel application run the following code in terminal.

composer create-project laravel/laravel reactjs-upload-app

cd reactjs-upload-app

Note:reactjs-upload-app” is a laravel application name.

Installing fresh new Laravel 9 Application
Installing fresh new Laravel 9 Application

Step 2: Creating Database and Configuration

Now next step is to create a database. To create a database first open phpmyadmin and create a database with name “reactjs-upload-app” (you can use anything you like).

Creating Database
Creating Database

Now enter the database details to .env file of laravel application.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=reactjs-upload-app
DB_USERNAME=root
DB_PASSWORD=
Database Configuration
Database Configuration

Step 3: Creating Auth with Breeze

Now we are going to create auth with breeze. To install a breeze library run the following command.

composer require laravel/breeze --dev

Now we are going to create authentication with login, register, email verification etc. To create authentication run the following command.

php artisan breeze:install react

Let’s install node js package:

npm install

Now run vite, you need to keep it started with the following command:

npm run dev

Run the migration:

php artisan migrate

Also Read: How to create SEO friendly sluggable URL Laravel 9 Example

Step 4: Creating Migration and Model

Now we are going to create migration for files table to save the upload image details to table. To create a migration file run the following command:

php artisan make:migration create_files_table

Now update the files migration with the following code.

<?php

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');
    }
};
Creating Migration - React JS Image Upload using Vite in Laravel 9 Example
Creating Migration

now run the migration

php artisan migrate

Now we are going to create a File model. To create a File model run the following code in terminal.

php artisan make:model File

and update with the following code.

<?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),
        );
    }
}
Creating Model - React JS Image Upload using Vite in Laravel 9 Example
Creating Model

Also Read: Restrict User Access from IP Address in Laravel 9 Tutorial

Step 5: Creating Route

Now we will create a route for react js image upload. Add the route to your routes/web.php as shown below.

<?php

use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;

use App\Http\Controllers\FileController;

/*
|--------------------------------------------------------------------------
| 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('/', function () {
    return Inertia::render('Welcome', [
        'canLogin' => Route::has('login'),
        'canRegister' => Route::has('register'),
        'laravelVersion' => Application::VERSION,
        'phpVersion' => PHP_VERSION,
    ]);
});

Route::get('/dashboard', function () {
    return Inertia::render('Dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

require __DIR__.'/auth.php';

//ReactJs Image Upload Routes
Route::get('file-upload', [FileController::class, 'index'])->name('file.upload');
Route::post('file-upload', [FileController::class, 'store'])->name('file.upload.store');
Routes - React JS Image Upload using Vite in Laravel 9 Example
Routes

Step 6: Creating Controller

Next we will create FileController file. First open app/Http/Controllers folder and create a new file FileController.php and add the following code into it.

app/Http/Controllers/FileController.php

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Validator;
use App\Models\File;
 
class FileController 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|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ])->validate();
  
        $fileName = time().'.'.$request->file->extension();  
        $request->file->move(public_path('uploads'), $fileName);
    
        File::create([
            'title' => $request->title,
            'name' => $fileName
        ]);
    
        return redirect()->route('file.upload');
    }
}
Creating Controller - React JS Image Upload using Vite in Laravel 9 Example
Creating Controller

Also Read: Livewire Pagination Laravel 9 Example Tutorial

Step 7: Creating React Pages

Now we are going to create React FileUpload.jsx page. Create a new file with name “FileUpload.jsx” inside resources/js/Pages and add the following code.

resources/js/Pages/FileUpload.jsx

import React from 'react';
import Authenticated from '@/Layouts/Authenticated';
import { Head, useForm, usePage, Link } from '@inertiajs/inertia-react';
  
export default function Dashboard(props) {
    const { files } = usePage().props
  
    const { data, setData, errors, post, progress } = useForm({
        title: "",
        file: null,
    });
  
    function handleSubmit(e) {
        e.preventDefault();
        post(route("file.upload.store"));
  
        setData("title", "")
        setData("file", null)
    }
    
    return (
        <Authenticated
            auth={props.auth}
            errors={props.errors}
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">React JS Image Upload using Vite in Laravel 9 Example - LaravelTuts.com</h2>}
        >
            <Head title="Posts" />
  
            <div className="py-12">
                <div className="max-w-7xl mx-auto sm:px-6 lg:px-8">
                    <div className="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                        <div className="p-6 bg-white border-b border-gray-200">
  
                            <form name="createForm" onSubmit={handleSubmit}>
                                <div className="flex flex-col">
                                    <div className="mb-4">
                                        <label className="">Title</label>
                                        <input
                                            type="text"
                                            className="w-full px-4 py-2"
                                            label="Title"
                                            name="title"
                                            value={data.title}
                                            onChange={(e) =>
                                                setData("title", e.target.value)
                                            }
                                        />
                                        <span className="text-red-600">
                                            {errors.title}
                                        </span>
                                    </div>
                                    <div className="mb-0">
                                        <label className="">File</label>
                                        <input
                                            type="file"
                                            className="w-full px-4 py-2"
                                            label="File"
                                            name="file"
                                            onChange={(e) =>
                                                setData("file", e.target.files[0])
                                            }
                                        />
                                        <span className="text-red-600">
                                            {errors.file}
                                        </span>
                                    </div>
                                </div>
  
                                {progress && (
                                  <div 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={progress.percentage}> {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>
  
                            <br/>
  
                            <h1 className='font-bold text-2xl text-center mb-2'>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 w-[200px]">Image</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {files.map(({ id, title, name }) => (
                                        <tr>
                                            <td className="border px-4 py-2">{ id }</td>
                                            <td className="border px-4 py-2">{ title }</td>
                                            <td className="border px-4 py-2">
                                                <img src={name} width="200px" />
                                            </td>
                                        </tr>
                                    ))}
  
                                    {files.length === 0 && (
                                        <tr>
                                            <td
                                                className="px-6 py-4 border-t"
                                                colSpan="3"
                                            >
                                                No Image found! Upload Some Image.
                                            </td>
                                        </tr>
                                    )}
                                </tbody>
                            </table>
  
                        </div>
                    </div>
                </div>
            </div>
        </Authenticated>
    );
}

Step 8: Testing

Now its time to test our react js image upload laravel application. Start a laravel server by running. following command.

php artisan serve

Also keep running vite by running following command.

npm run dev

or

npm run build

Now, Open the following URL in any web browser

http://127.0.0.1:8000/

Previews:

React JS Image Upload using Vite in Laravel 9 Example
React JS Image Upload using Vite in Laravel 9 Example

Step 9: Conclusion

Today, We had learn React JS Image Upload using Vite in Laravel 9 Example. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: Enum Model Attribute Casting in Laravel 9 Example

3 Comments

Leave a Reply