Tinkerwell - The PHP Scratchpad

Uploading Avatar Images with Spatie’s Media Library

Published on by

Uploading Avatar Images with Spatie’s Media Library image

By default, the Laravel registration form contains only the name, email, and password, but often it’s useful to allow the user to upload a photo or an avatar. In this tutorial we will show you an easy way to add it, using Spatie’s Media Library package.

Step 1. Change the User Registration Form

Let’s add a file upload field called Avatar to the default Laravel registration form:

<!-- resources/views/auth/register.blade.php -->
 
<div class="form-group row">
<label for="avatar" class="col-md-4 col-form-label text-md-right">{{ __('Avatar (optional)') }}</label>
 
<div class="col-md-6">
<input id="avatar" type="file" class="form-control" name="avatar">
</div>
</div>

Step 2. Upload and Store with the Media Library

Default Laravel registration is handled in app/Http/Controllers/Auth/RegisterController.php, specifically in method create():

/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}

Here we need to add our logic to upload our avatar and store it into the database. Guess what – here’s where Spatie Media Library comes to help us. Let’s install it:

composer require spatie/laravel-medialibrary:^7.0.0

After the install:

php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="migrations"

Finally, as we have migrations in our published folder:

php artisan migrate

It will create a database table called media which uses Polymorphic Relations to store the data. In our case – we will attach media files to app\User model.

Now, let’s prepare that app\User.php model to work with Media Library. Here’s what we need to add:

  • Two use statements outside of the class
  • Class implements HasMedia
  • One use statement inside of the class
// These two come from Media Library
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\HasMedia\HasMedia;
 
class User extends Authenticatable implements HasMedia
{
// ...
use HasMediaTrait;
}

Now, let’s go back to our RegisterController and add some code to the create() method:

protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
 
if (isset($data['avatar'])) {
$user->addMediaFromRequest('avatar')->toMediaCollection('avatars');
}
 
return $user;
}

What we’ve done here:

  • Checking if the avatar is present, then we use Media Library to upload a file from the request and add it to media collection in the database;
  • We can do it only by attaching to existing user, so we do it after the user is created, and then return the final result as a User object.

Here’s the result how the file is stored:

Notice: by default, Laravel stores all files in storage/app/public, don’t forget to run command php artisan storage:link or change your folders settings in config/filesystems.php file.

And this is what is stored in the database:

Step 3. Show an Avatar Thumbnail in the Top Navigation

The most straightforward use of that avatar is to show it on the top-right corner near the user’s name, so let’s do that.

But first, what if the uploaded file is huge? How could we resize it to, say, 50×50? This is where Media Library will help us again. All we need to do is define resize rules in the same app\User model:

use Spatie\MediaLibrary\Models\Media;
 
class User extends Authenticatable implements HasMedia
{
// ... all other code
 
public function registerMediaConversions(Media $media = null)
{
$this->addMediaConversion('thumb')
->width(50)
->height(50);
}
}

And now we have a rule called thumb which we can use to show the thumbnail. When uploading, it will be automatically stored in conversions sub-folder for that item:

Finally, this is how we show the avatar:

<!-- resources/views/layouts/app.blade.php -->
 
<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
<img src="{{ Auth::user()->getMedia('avatars')->first()->getUrl('thumb') }}">
{{ Auth::user()->name }} <span class="caret"></span>
</a>

Yes, exactly, this is one line we need:

Auth::user()->getMedia('avatars')->first()->getUrl('thumb')

We’re taking User model object, then get all the media files from avatars collection, then take the first and get the URL for the conversion called thumb we described above.

Here’s final visual result:

That’s it. Of course, you may go much deeper, like showing the avatar original image and allow users to resize/crop it themselves with some JavaScript library, then edit avatar in a separate Settings page, etc. I will leave it to you, or maybe to the potential future “episode 2” of this article.

More links on the subject of this tutorial:

PovilasKorop photo

Creator of Courses and Tutorials at Laravel Daily

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
"The Vibes" — NativePHP Hosts a Day 3 after Laracon US image

"The Vibes" — NativePHP Hosts a Day 3 after Laracon US

Read article
What We Know About Laravel 13 image

What We Know About Laravel 13

Read article
New Colors Added in Tailwind CSS v4.2 image

New Colors Added in Tailwind CSS v4.2

Read article
Factory makeMany() Method in Laravel 12.52.0 image

Factory makeMany() Method in Laravel 12.52.0

Read article
Laravel Adds an Official Svelte + Inertia Starter Kit image

Laravel Adds an Official Svelte + Inertia Starter Kit

Read article
MongoDB Vector Search in Laravel: Finding the Unqueryable image

MongoDB Vector Search in Laravel: Finding the Unqueryable

Read article