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.

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
Lucky Media logo

Lucky Media

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

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
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
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
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

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

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article