How to Upload Files from React js to Laravel 10 API

11 months 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

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...


API Authentication Using Laravel Sanctum and React js Part 2

In the second part of this tutorial, we will start handling the frontend first, we will create the r...


API Authentication Using Laravel Sanctum and React js Part 1

In today's tutorial, we are going to see how to create a token-based authentication system using Lar...


How to Update Nested Array with Hooks in React

In this lesson, we will see how to update nested array with hooks in React, let's assume that we hav...


How to Set the Loading State Only on a Specific Clicked Button in React

In this lesson, we will see how to set the loading state only on a specific clicked button in React,...


Create a Rest API in PHP and Consume it in React Part 5

In the fifth part of this tutorial, we will add routes to our application and finally, we will add s...