How to upload and get image with API using Laravel Storage?

If you developing a web project usually their will be involved in storing image, getting image response. This article will introduce you on how to upload image to laravel storage and get image response from storage and show it by API.

Register route API

  • Creating route get image/{path} that call to getImage to get image response
  • Creating route upload image that call to uploadImage method to upload image to Laravel storage system
<?php

use App\Http\Controllers\ImageController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::get('image/{path}', [ImageController::class, 'getImage'])->where('path', '.*');
Route::post('image', [ImageController::class, 'uploadImage']);

Creating ImageController

For upload image to storage and get image from storage

Storage::putFile() first parameter is path, second is image file

If the path is 'image' when upload image the image will store in storage/app/image/image_path.jpg

Storage::get() expected path parameter and return in raw image file

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ImageController extends Controller
{
    public function uploadImage(Request $request)
    {
        $path = Storage::putFile('image', $request->image);
        return response()->json(['path' => $path]);
    }

    public function getImage($path)
    {
        $image = Storage::get($path);
        return response($image, 200)->header('Content-Type', Storage::getMimeType($path));
    }
}

Test upload image and get image with Insomnia

Upload image with API

url/api/image (POST METHOD)

Get image by API

url/api/image/image/wCQJTIenXZA3t9I9WGkg3WEpZH91Hwg57FwmlzRU.png (GET METHOD)