Laravel 11 - How To Generate Avatar

Touseef Afridi
24 Sep 24

Laravel 11 - How To Generate Avatar

In this tutorial, we will cover how to generate avatars using a full name in Laravel 10, which adds personalization and enhances user profile visuals.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through the process of setting up a Laravel project with Breeze authentication and generating user avatars. You'll start by creating a new Laravel project and configuring authentication with Breeze. Then, you'll add an avatar column to the users table and install the Laravolt Avatar package to generate personalized avatars during registration. The avatar will be stored in the storage directory and associated with the user. You'll also update the user model, publish the configuration, and create a symbolic storage link. Finally, the guide shows you how to display the avatar in the navigation bar and test the functionality by registering a new user and verifying the avatar display on the dashboard.

Step # 1 : Create a Fresh Laravel Project with Breeze Authentication.

Note: You can use any authentication method of your choice (Breeze, Jetstream, custom authentication, etc.). This is important because we will use the authenticated user’s name to generate an avatar. You can turn the name, email, or any other string into an initial-based avatar or Gravatar. 
To begin, you can either use an existing Laravel project or create a new one with authentication. If Laravel is installed globally, run the following command.
laravel new avatar
Alternatively, if you're using Composer, run.
composer create-project laravel/laravel --prefer-dist avatar
During the setup process, you’ll be prompted with several options.
  • Starter Kit: Select Breeze for lightweight authentication.
  • Stack: Choose Blade for the frontend.
  • Dark Mode Support: Select No.
  • Testing Framework: Choose PHPUnit.
  • Initialize Git Repository: Select No.
  • Database: Choose MySQL as your preferred driver.
  • Run Migrations: Select No, since we’ll add an additional field to store the avatar later.

This will create a new Laravel project named avatar, configured with authentication via Breeze and Blade, ready for adding avatar generation functionality.

Step # 2 : Access the project.

Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
cd c:xampp/htdocs/avatar
This ensures you're in the correct folder to run Artisan commands and manage your project files.

Step # 3 : Add Avatar Column and Run Migrations.

To store user avatars, you'll need to add a new avatar column to the users table. Open the create_users_table migration file located at: database/migrations/{timestamp}_create_users_table.php. Update the migration file to include the avatar column like this
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('avatar'); // Add avatar column for user avatar
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
        Schema::create('password_reset_tokens', function (Blueprint $table) {
            $table->string('email')->primary();
            $table->string('token');
            $table->timestamp('created_at')->nullable();
        });
        Schema::create('sessions', function (Blueprint $table) {
            $table->string('id')->primary();
            $table->foreignId('user_id')->nullable()->index();
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->longText('payload');
            $table->integer('last_activity')->index();
        });
    }
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('users');
        Schema::dropIfExists('password_reset_tokens');
        Schema::dropIfExists('sessions');
    }
};
Once you've updated the migration, run the migration command.
php artisan migrate
If the database doesn't exist, you'll see a prompt like this.
Warn : The database 'avatar' does not exist on the 'mysql' connection.
Would you like to create it? (yes/no) [yes]
Type yes and press Enter to proceed.
This step ensures your users table is ready to store avatar paths, which will later be used to display user profile images throughout your application.

Step # 4 : Update the User Model to Include Avatar.

Navigate to the User model located at app/Models/User.php and add the avatar field to the $fillable property to allow mass assignment.
    protected $fillable = [
        'name',
        'email',
        'password',
        'avatar',
    ];
This step ensures that when you create or update a user using mass assignment (like $user->update($request->all())), the avatar value will be saved along with other fields.

Step # 5 : Install the Laravolt Avatar Package.

To generate avatars automatically, install the Laravolt Avatar package by running the following command.
composer require laravolt/avatar
This package allows you to easily generate text-based avatars from user names, which is especially useful when users do not upload a profile picture. Once installed, Laravolt Avatar will automatically register itself, providing you with an easy-to-use API for generating avatars based on initials or other customizations.

Step # 6 : Publish the configuration.

Run the following command to publish the configuration.
php artisan vendor:publish --provider="Laravolt\Avatar\ServiceProvider"
This command will publish the package's configuration file, allowing you to customize the avatar settings according to your needs.

Step # 7 : Create a storage link.

Run the following command to create a symbolic link to the storage directory.
php artisan storage:link
This command will create a link from the public directory to the storage folder, making files stored in the storage folder accessible via a URL.

Step # 8 : Create avatar.

Navigate to the RegisteredUserController located at app/Http/Controllers/Auth/RegisteredUserController.php and add the logic to generate a personalized avatar during user registration using the Laravolt\Avatar package, ensuring the avatar is saved in the storage directory after the user details have been validated.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;
// Include the Avatar facade
use Laravolt\Avatar\Facade as Avatar;
class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(): View
    {
        return view('auth.register');
    }
    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);
        // Create avatar for the user based on their name
        // Unique path for the avatar
        $avatarPath = 'storage/avatar_' . time() . '.png';
        Avatar::create($request->name)
            ->setDimension(300, 300) // Set width and height
            ->setFontSize(150) // Set font size for the text
            ->save(storage_path('app/public/' . $avatarPath));
        // Create the user with the avatar path
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'avatar' => $avatarPath, // Store the path to the avatar
        ]);
            event(new Registered($user));
            Auth::login($user);
            return redirect(route('dashboard', absolute: false));
        }
    }
In this step, during the user registration process, we generate a personalized avatar for the user using their name, leveraging the Laravolt\Avatar package. The avatar is created, saved in the storage directory, and its path is stored in the avatar column of the users table. This ensures that each registered user receives a unique avatar, which is linked to their profile. After the user is successfully created, they are logged in automatically and redirected to the dashboard.

Step # 9 : Display Avatar.

Open the views/layouts/navigation.blade.php file and insert the following code just before displaying the username.
<img src="{{ asset('storage/' . Auth::user()->avatar) }}" width="30" style="margin-right: 0.25rem">
This will display the user's avatar next to their username in the navigation bar.

Step # 10 : It's time to test.

Start the Laravel development server.
php artisan serve
Next, open your browser and navigate to the following URL:127.0.0.1:8000/register.
Create a new account, and once the registration is successful, you will be redirected to the dashboard where you can view the user's avatar displayed alongside their details.

Conclusion

By following this guide, you've successfully implemented user avatar generation in your Laravel project using the Laravolt Avatar package. Your application now automatically creates personalized avatars for users upon registration, ensuring each user has a unique image associated with their profile. You've also learned how to store the avatar in the storage directory, display it in the navigation bar, and test the functionality to ensure a seamless user experience. This setup enhances the personalization of your application and provides a more engaging user interface.
For more details, please refer to the Laravolt Avatar package documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering