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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Validate uploads tightly by type, mime, and size before touching the filesystem.
  2. 2Normalizing images to a fixed size and format keeps storage predictable and cacheable.
  3. 3Write the new file first and delete the old one only after, so a failure never leaves a user without an avatar.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Handling avatar uploads in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code