How to Upload Files from React js to Laravel 10 API

1 year ago admin Reactjs

In this tutorial, we will see how to upload files from react js to Laravel 10 API, let's assume that we have a react js app and the user wants to update his profile image, so let's see how we can do that.


Get user data from the react js front end

In the front end, we use the form data interface, all we have to do is to append the values and send them to the Laravel API using Axios.

                                                    
                                                                                                                
import React from 'react';
import { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { BASE_URL } from '../../Helpers/Url';
import { toast } from 'react-toastify';
import { setCurrentUser } from '../../redux/slices/userSlice';
import axios from 'axios';

export default function ProfileSidebar() {
    const [image, setImage] = useState('');
    const { user, token } = useSelector(state => state.user);
    const dispatch = useDispatch();
    const config = {
        headers: {
            "Content-type": "multipart/form-data",
            "Authorization": `Bearer ${token}`,
        }
    };

    const updateProfileImage = async () => {
        try {
            const formData = new FormData();
            formData.append('user_image', image);
            formData.append('_method', 'put');
            const response = await axios.post(`${BASE_URL}user/update/${user.id}`, formData, config);
            dispatch(setCurrentUser(response.data.user));
            setImage('');
            toast.success("Your profile image has been updated !", {
                position: toast.POSITION.TOP_RIGHT
            });
          } catch (error) {
              console.log(error)
          }
    }

    return (
        <div className="col-md-4">
            <div className="card p-2">
                <div className="d-flex flex-column justify-content-center align-items-center">
                    <img src={user.image_url} 
                        width={150}
                        height={150}
                        className="rounded-circle"
                        alt="Profile Image" />
                    <div className="input-group my-3">
                        <input type="file" 
                            name="user_image"
                            onChange={(e) => setImage(e.target.files[0])}
                            accept="image/*"
                            className="form-control" />
                        <button disabled={!image} 
                            onClick={() => updateProfileImage()}
                            className="btn btn-sm btn-primary">
                            Upload
                        </button>
                    </div>
                </div>
            </div>
        </div>
    )
}


Store data in the database

Next, we get and store data in the UserController.

                                                        
                                                                                                                        
<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\File;

class UserController extends Controller
{
    /**
     * Update user profile
     */
    public function updateUserProfile(User $user, Request $request) {
        if($request->has("user_image")) {
            $path = public_path('storage/images/users/');
            if(File::exists($path.$user->profile_image)) {
                File::delete($path.$user->profile_image);
            }
            $user_image = $request->file('user_image');
            $user_image_name = time() . '_' . 'user'. '_' . $user_image->getClientOriginalName();
            $user_image->storeAs('images/users/', $user_image_name, 'public');
            $user->update([
                'profile_image' => $user_image_name
            ]);
        }
    }
}


Adding the route

Finally, we add the route.

                                                        
                                                                                                                        
Route::middleware('auth:sanctum')->group(function() {
    Route::put('user/update/{user}',[UserController::class,'updateUserProfile']);
});

Related Tuorials

Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 5

In the last part of this tutorial, we will display the cart items, add the ability to increment/decr...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 4

In the fourth part of this tutorial, we will fetch and display all the products on the home page, an...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 3

In the third part of this tutorial, we will start coding the front end, first, we will install the p...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 2

In the second part of this tutorial, we will create the product and payment controllers, and later w...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 1

In this tutorial, we will create a shopping cart using React js Laravel 11 and Stripe payment gatewa...


How to Use Rich Text Editor in React js

In this lesson, we will see how to use rich text editor in React JS, let's assume that we have a com...


How to Download a File from the Server Using Laravel and React js

In this tutorial, we will see how to download a file from the server using Laravel and React js, let...


How to Add a Class on Hover in React js

In this lesson, we will see how to add a class on hover in React js, let's assume that we have a boo...


Drag and Drop Image and File Upload Using React and Laravel

In this tutorial, we will see how to upload files using drag and drop in React js and Laravel, first...


API Authentication Using Laravel Sanctum and React js Part 3

In the third part of this tutorial, we will register and log in the user, get the access token, and...