php
40 lines · 8 steps
Handling avatar uploads in Laravel
A Laravel controller that validates, resizes, stores, and swaps a user's avatar image in one request.
Explained by
highlit
1<?php
2
3namespace App\Http\Controllers;
4
5use Illuminate\Http\Request;
6use Illuminate\Support\Facades\Storage;
7use Intervention\Image\Facades\Image;
8
9class AvatarController extends Controller
10{
11 public function update(Request $request)
12 {
13 $validated = $request->validate([
14 'avatar' => ['required', 'image', 'mimes:jpeg,png,webp', 'max:4096'],
15 ]);
16
17 $user = $request->user();
18
19 $resized = Image::make($validated['avatar'])
20 ->fit(256, 256)
21 ->encode('webp', 85);
22
23 $path = sprintf('avatars/%s/%s.webp', $user->id, bin2hex(random_bytes(8)));
24
25 Storage::disk('public')->put($path, (string) $resized, [
26 'visibility' => 'public',
27 'CacheControl' => 'max-age=31536000',
28 ]);
29
30 if ($user->avatar_path) {
31 Storage::disk('public')->delete($user->avatar_path);
32 }
33
34 $user->update(['avatar_path' => $path]);
35
36 return response()->json([
37 'avatar_url' => Storage::disk('public')->url($path),
38 ]);
39 }
40}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Validate uploads tightly by type, mime, and size before touching the filesystem.
- 2Normalizing images to a fixed size and format keeps storage predictable and cacheable.
- 3Write the new file first and delete the old one only after, so a failure never leaves a user without an avatar.
Related explainers
go
package main import ( "errors"
Parsing and validating CLI flags in Go
cli-parsing
validation
error-handling
Intermediate
8 steps
javascript
'use server' import { revalidatePath } from 'next/cache' import { redirect } from 'next/navigation'
How a Next.js Server Action updates a post
server-actions
authorization
validation
Intermediate
7 steps
php
<?php namespace App\Support;
Locale-aware formatting with PHP's intl extension
internationalization
encapsulation
constructor-injection
Intermediate
7 steps
php
<?php namespace App\Support;
Merging query params onto a URL in PHP
url-parsing
query-strings
immutability
Intermediate
8 steps
php
<?php class ImageUploadService {
Validating file uploads safely in PHP
file-upload
input-validation
security
Intermediate
8 steps
php
<?php namespace App\View;
Building a safe HTML escaper in PHP
security
xss
escaping
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/handling-avatar-uploads-in-laravel-explained-php-fd82/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.