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

As a developer, you may have encountered situations where you need to upload images from a React Native app to a Laravel API. While it may seem like a daunting task, it’s actually quite straightforward once you understand the process. In this article, we’ll walk you through the steps to upload images from a React Native app to a Laravel API.

Setting Up the Laravel API

First, let’s start by setting up our Laravel API. We’ll create a new Laravel project and define the API endpoint for image uploads.

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

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

“`php
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.

“`php
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’ => ‘required|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.

bash
npm install expo-image-picker

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

“`jsx
import React, { useState } from ‘react’;
import { View, Text, Button, Image } from ‘react-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': 'multipart/form-data',
        },
        body: formData,
    });

    const data = await response.json();

    console.log(data);
};

return (
    <View>
        <Button title="Pick an image" onPress={pickImage} />
        {image && (
            <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
        )}
        <Button title="Upload image" onPress={uploadImage} />
    </View>
);

};

export default ImageUploadComponent;
“`

Conclusion

In this article, we walked through the steps to upload images from a React Native app to a Laravel API. We set up our Laravel API to handle image uploads, created a new component in our React Native app to select and upload images, and used the fetch API to send the image data to our Laravel API. By following these steps, you should be able to upload images from your React Native app to your Laravel API.

Leave a Reply

Your email address will not be published. Required fields are marked *