How To Upload Image In Laravel 9 Using React JS

In this step, we will see how to upload images in laravel 9 using react js. Here, we will learn about react js image upload using vite in laravel 9 and laravel 10. Also, we will install laravel breeze, inertia js, vite, and tailwind CSS to create react js image upload with a progress bar using laravel 9 and laravel 10.

React is a free and open-source front-end JavaScript library for building user interfaces based on UI components.

Vite js is a rapid development tool for modern web projects. It focuses on speed and performance by improving the development experience.

So, let's see laravel 9 react js image upload using vite, react js image upload using vite in laravel 9/10, how to upload image in laravel 9/10, image upload using vite in laravel 9 and laravel 10, laravel image upload using vite.

Step 1: Install Laravel 9/10

Step 2: Create Auth with Breeze

Step 3: Create Migration and Model

Step 4: Create Route

Step 5: Create Controller

Step 6: Create React Pages

Step 7: Run Laravel 9 Application

 

 Step 1: Install Laravel 9/10

In this step, we will install laravel 9 using the following command.

composer create-project laravel/laravel laravel_9_react_js_img_upload

 

Step 2: Create Auth with Breeze

Now, we will install laravel/breeze using the following composer command.

composer require laravel/breeze --dev

After that, we will create authentication using the below command. This command creates a login, register, and email verification system.

php artisan breeze:install react

Now, we will install the node js package and run the npm using the following command.

npm install

npm run dev

After that, we will migrate the table to the database using the below command.

php artisan migrate

 

 

Step 3: Create Migration and Model

In this step, we will create a model and migration using the following command.

php artisan make:migration create_images_table

Migration:

<?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('images', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('name');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
};

Now, we will migrate the images table to the database.

php artisan migrate

Now, we will create an Image model using the below command.

php artisan make:model Image

app/Models/Image.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
  
class Image 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: Create Route

In this step, we will create routes in the web.php file.

routes/web.php

<?php
 
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageController;
  
/*
|--------------------------------------------------------------------------
| 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('image-upload', [ImageController::class, 'index'])->name('image.upload');
Route::post('image-upload', [ImageController::class, 'store'])->name('image.upload.store');

 

 

Step 5: Create Controller

Now, we will create an ImageController file. So, add the below code to that file.

app/Http/Controllers/ImageController.php

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

 

Step 6: Create React Pages

Now, we will create ImageUpload.jsx file. So, add the following code to that file.

resources/js/Pages/ImageUpload.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 { images } = usePage().props
  
    const { data, setData, errors, post, progress } = useForm({
        title: "",
        image: null,
    });
  
    function handleSubmit(e) {
        e.preventDefault();
        post(route("image.upload.store"));
  
        setData("title", "")
        setData("image", null)
    }
    
    return (
        <Authenticated
            auth={props.auth}
            errors={props.errors}
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">How To Upload Image In Laravel 9 Using React JS - Techsolutionstuff</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="">Image</label>
                                        <input
                                            type="file"
                                            className="w-full px-4 py-2"
                                            label="Image"
                                            name="image"
                                            onChange={(e) =>
                                                setData("image", e.target.images[0])
                                            }
                                        />
                                        <span className="text-red-600">
                                            {errors.image}
                                        </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>Uploaded Images 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>
                                    {images.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>
                                    ))}
  
                                    {images.length === 0 && (
                                        <tr>
                                            <td
                                                className="px-6 py-4 border-t"
                                                colSpan="4"
                                            >
                                                No contacts found.
                                            </td>
                                        </tr>
                                    )}
                                </tbody>
                            </table>
  
                        </div>
                    </div>
                </div>
            </div>
        </Authenticated>
    );
}

 

 

Step 7: Run Laravel 9 Application

Now, we will run laravel 9 react js image upload using vite using the following command.

php artisan serve

After that, run the dev command.

npm run dev

npm run build

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS