$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[April 18, 2025] Laravel

Laravel File Uploads: Storage Tips

Laravel File Uploads: Storage Tips

────────────────────────────────────────────────────────

Laravel File Uploads: Storage Tips

Tip: Validate File Uploads

$request->validate([
    'avatar' => 'required|image|mimes:jpeg,png|max:2048',
]);

max is in kilobytes. 2048 = 2MB.

Gotcha: store() Generates Random Names

$path = $request->file('avatar')->store('avatars');

Returns a hash filename. Use storeAs() to keep the original name.

Tip: Multiple Disks

Storage::disk('s3')->put('file.txt', $content);
Storage::disk('local')->put('file.txt', $content);

Gotcha: Missing Files Don't Throw Errors

Storage::get('nonexistent.txt') returns null, not an exception.

Tip: Temporary URLs

$url = Storage::disk('s3')->temporaryUrl('file.pdf', now()->addMinutes(5));

Gotcha: storage:link Symlink

php artisan storage:link

Creates a symlink from public/storage to storage/app/public.

Tip: Use route:cache Carefully

php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.

Tip: Model APP_KEY Rotation

Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.

Gotcha: Local Scope Leaks

Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.

Senior Insight

One pattern I've adopted after years of Laravel development is treating every feature as if it will need to be debugged at 3 AM. This means explicit logging, observable queue jobs, and defensive coding. The extra 10 minutes it takes to add structured logging to a new feature is nothing compared to the hours saved when the pager goes off. I've learned that maintainability isn't about elegant code — it's about code that can be understood and fixed under pressure.

Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)

────────────────────────────────────────────────────────
<-- back to posts