Uploading Images from React Native to Laravel API: A Step-by-Step Guide

Setting Up the Laravel API

To set up our Laravel API, we’ll create a new Laravel project and define the API endpoint for image uploads.

composer create-project --prefer-dist laravel/laravel project-name

Next, we’ll create a new migration to define the schema for our images table.


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateImagesTable extends Migration
{
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('image');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('images');
    }
}

Creating the API Endpoint

Now that we have our schema defined, let’s create the API endpoint for image uploads. We’ll create a new controller to handle the image upload request.


use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ImageUploadController extends Controller
{
    public function uploadImage(Request $request)
    {
        // Validate the request
        $this->validate($request, [
            'image' => 'equired|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        // Store the image
        $image = $request->file('image');
        $imageName = time().'.'.$image->getClientOriginalExtension();
        $image->move(public_path('images'), $imageName);

        // Return a response
        return response()->json(['message' => 'Image uploaded successfully']);
    }
}

Configuring the React Native App

Now that we have our Laravel API set up, let’s configure our React Native app to upload images to the API. We’ll use the expo-image-picker library to select images from the device’s gallery.

npm install expo-image-picker

Next, we’ll create a new component to handle the image upload.


import React, { useState } from 'eact';
import { View, Text, Button, Image } from 'eact-native';
import * as ImagePicker from 'expo-image-picker';

const ImageUploadComponent = () => {
    const [image, setImage] = useState(null);

    const pickImage = async () => {
        const result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 1,
        });

        if (!result.cancelled) {
            setImage(result.data);
        }
    };

    const uploadImage = async () => {
        const formData = new FormData();
        formData.append('image', image);

        const response = await fetch('https://example.com/api/image-upload', {
            method: 'POST',
            headers: {
                'Content-Type': 'ultipart/form-data',
            },
            body: formData,
        });

        const data = await response.json();

        console.log(data);
    };

    return (
        
            

Leave a Reply