A phone photo can contain far more pixels than a Laravel page needs. If a card displays an image at 600 pixels wide, making the browser download the original photograph wastes bandwidth before CSS shrinks it. I would resize the upload once, save the result and serve that smaller file.
This tutorial builds a signed-in upload endpoint that accepts JPEG or PNG, fits the image inside a 1200-pixel square without stretching or enlarging it, and saves WebP on Laravel's public disk. The code uses Intervention Image 4. I ran the request rules, action and controller in an isolated Laravel project with real image files; the results are below.
Start with a Laravel 13 application that already has authentication. The official integration package registers the image manager for dependency injection and supplies a publishable configuration file:
composer require intervention/image-laravel:^4.0
php artisan vendor:publish --provider="Intervention\Image\Laravel\ServiceProvider"
php artisan storage:linkThe verification environment used PHP 8.4.27, Laravel 13.40.0, Intervention Image 4.4.1 and its Laravel integration 4.1.1. Keep the resulting lockfile in version control. Older tutorials use different APIs; this example deliberately follows the version 4 documentation.
The library requires PHP 8.3 or later, Mbstring and a supported image-processing extension. Laravel 13 has its own PHP requirement. Here we explicitly choose GD, with JPEG, PNG and WebP support. Install and check those capabilities in the PHP runtime handling uploads, and in workers if you later move processing to a queue. Exif support is recommended for orientation.
Set config/intervention-image.php to the following. Automatic orientation handles supported orientation metadata; stripping removes metadata from the encoded result. Disabling animation decoding keeps this endpoint focused on still images:
<?php
declare(strict_types=1);
return [
'driver' => Intervention\Image\Drivers\Gd\Driver::class,
'options' => [
'autoOrientation' => true,
'decodeAnimation' => false,
'backgroundColor' => 'ffffff',
'strip' => true,
],
];
A landscape photograph and a portrait photograph should not both become a stretched square. scaleDown() preserves the original aspect ratio and fits within the supplied bounds. A 2400-by-1600 image becomes 1200 by 800. A 320-by-200 upload stays that size.
For an avatar, you may want a square crop instead. Intervention's cover() combines cropping and resizing; coverDown() also avoids upscaling, so a small source may produce smaller dimensions than requested. Those are different product decisions. This endpoint keeps the complete photograph, which is why its action uses scaleDown. The resizing documentation shows the differences.
Create app/Http/Requests/StoreImageRequest.php. Authentication determines who can upload; validation determines what they can submit. In an application with roles, tighten authorization to the appropriate policy or permission.
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Dimensions;
final class StoreImageRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/** @return array<string, list<string|Dimensions>> */
public function rules(): array
{
return [
'image' => [
'bail',
'required',
'file',
'max:5120',
'image',
'mimetypes:image/jpeg,image/png',
(new Dimensions)->maxWidth(4000)->maxHeight(4000),
],
];
}
}
The maximum upload size is 5120 KiB, or 5 MiB. The dimension limits allow at most 4000 by 4000 pixels. Both limits matter: a heavily compressed file can be small on disk but expensive to decode. The bail rule stops further checks after a failure, and the size check comes before image inspection.
The MIME rule inspects file content rather than trusting the browser's claimed content type or the filename. A text file named photo.jpg must fail. This endpoint intentionally excludes SVG, GIF and other formats. Laravel's file validation documentation explains the available rules.
These bounds reduce resource use; they do not establish a universal safe memory limit. Decoding and resizing allocate working buffers. Set PHP upload limits and your web server's request-body limit consistently, budget memory for concurrent requests, and measure with representative photographs before raising the caps.
Create app/Actions/StoreResizedImage.php. The configured image manager is injected through its interface. The action decodes the temporary upload, resizes it, encodes WebP and stores only that result:
<?php
declare(strict_types=1);
namespace App\Actions;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Intervention\Image\Exceptions\DecoderException;
use Intervention\Image\Format;
use Intervention\Image\Interfaces\ImageManagerInterface;
use RuntimeException;
final readonly class StoreResizedImage
{
public function __construct(private ImageManagerInterface $images) {}
public function handle(UploadedFile $upload): string
{
try {
$image = $this->images->decodePath($upload->getPathname());
} catch (DecoderException) {
throw ValidationException::withMessages([
'image' => 'This image could not be decoded. Please export it again.',
]);
}
$encoded = $image
->scaleDown(width: 1200, height: 1200)
->encodeUsingFormat(Format::WEBP, quality: 80);
$path = 'images/'.Str::uuid().'.webp';
if (! Storage::disk('public')->put($path, (string) $encoded)) {
throw new RuntimeException('The resized image could not be stored.');
}
return $path;
}
}
The explicit format and the .webp extension agree. A quality value of 80 is a starting point, not a promised file size or percentage reduction. Photographic detail, noise and transparency affect the encoded size. Inspect your own output before choosing a quality setting for a product catalogue or portfolio.
The UUID prevents filename collisions and avoids reusing a client-supplied path. The action returns the stored relative path, which is what I would persist on a model. If decoding fails, the response identifies the image field. If storage fails, the action throws rather than returning a URL for a file that was never written.
Create app/Http/Controllers/StoreImageController.php. The form request runs before the controller, so its validated image is an uploaded file. Keep the controller responsible for the response:
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Actions\StoreResizedImage;
use App\Http\Requests\StoreImageRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
final class StoreImageController
{
public function __invoke(
StoreImageRequest $request,
StoreResizedImage $store,
): JsonResponse {
/** @var UploadedFile $upload */
$upload = $request->validated('image');
$path = $store->handle($upload);
return new JsonResponse([
'path' => $path,
'url' => Storage::disk('public')->url($path),
], 201);
}
}
Add this route to routes/web.php. It uses your existing session authentication and web middleware, including CSRF protection. The throttle limits repeated uploads:
<?php
use App\Http\Controllers\StoreImageController;
use Illuminate\Support\Facades\Route;
Route::post('/images', StoreImageController::class)
->middleware(['auth', 'throttle:10,1'])
->name('images.store');
A Blade form on a page available to signed-in users can submit to it. Keep the CSRF token and multipart encoding. The accept attribute helps the file picker, but the request rules still make the decision:
<form method="POST" action="{{ route('images.store') }}"
enctype="multipart/form-data">
@csrf
<label for="image">Choose a photograph</label>
<input id="image" type="file" name="image"
accept="image/jpeg,image/png" required>
@error('image')
<p>{{ $message }}</p>
@enderror
<button type="submit">Upload photograph</button>
</form>The endpoint returns JSON with the path and public URL. A JavaScript frontend can use that URL for its preview; a normal form submission displays the JSON response. The default public disk stores files under storage/app/public, and storage:link exposes them through public/storage. This is appropriate for public photographs. Private documents need private storage and an authorized delivery route.
I generated real PNG and JPEG fixtures and ran them through the published request rules and action using GD. The landscape output was 1200 by 800, the portrait output was 800 by 1200, and the small image remained 320 by 200. Each output preserved aspect ratio, stayed within the original dimensions, and had both a WebP MIME type and the WebP byte signature.
The checks also rejected an oversized dimension, a file over the byte limit, a missing upload and text disguised as JPEG. An undecodable input produced a field validation error. The controller returned 201 and a URL matching an actual stored file. Those checks cover the PHP implementation; deployment still needs its own upload, public-link and runtime-configuration check.