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
DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

Visit DocuWriter.ai
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

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

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
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
Bacancy logo

Bacancy

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

Bacancy
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Launch your Startup Fast with LaraFast image

Launch your Startup Fast with LaraFast

Read article
Embed Livewire Components on Any Website image

Embed Livewire Components on Any Website

Read article
Statamic announces next Flat Camp retreat (EU edition) image

Statamic announces next Flat Camp retreat (EU edition)

Read article
Laravel Herd releases v1.5.0 with new services. No more Docker, DBNGIN, or even homebrew! image

Laravel Herd releases v1.5.0 with new services. No more Docker, DBNGIN, or even homebrew!

Read article
Resources for Getting Up To Speed with Laravel 11 image

Resources for Getting Up To Speed with Laravel 11

Read article
Laravel 11 streamlined configuration files image

Laravel 11 streamlined configuration files

Read article