Join 25,000+ Laravel Developers and join the free Laravel Newsletter
Uploading Avatar Images with Spatie’s Media Library
Laravel Tutorials / March 23, 2018

Uploading Avatar Images with Spatie’s Media Library

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:

This appeared first on Laravel News
Laravel News Partners

Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.