Laravel 10 - How to Generate Avatar

Touseef Afridi
09 Sep 24

Laravel 10 - 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

In this guide, we walk you through how to integrate and display user avatars in a Laravel application during the registration process. You'll begin by setting up a Laravel project and installing Laravel Breeze for authentication. After that, we'll install the Laravolt Avatar package to generate avatars based on the user's name. The guide covers publishing the package's configuration, creating a storage link for avatar access, and updating the user registration process to automatically generate avatars. Finally, we’ll show you how to display the avatar in the navigation bar and test the functionality by running the Laravel development server. With these steps, you’ll be able to offer personalized avatars in your Laravel app.

Step # 1 : Set Up a Laravel Project.

You can either begin with a brand-new Laravel project or use an existing one. If you have Laravel globally installed use the following command.
laravel new laravolt
Or, if you want to use Composer. Use the following command.
composer create-project laravel/laravel --prefer-dist laravolt
Once you've run either command, Laravel will generate all the standard directories and files needed for your project. This includes the basic file structure for handling routing, views, controllers, models, and migrations. This setup ensures that you have a well-organized foundation for building your application, and you can immediately start implementing features like authentication, user management, and more.

Step # 2 : Navigate to the Project Directory.

Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
cd c:xampp/htdocs/laravolt
This just puts you inside your project so you can start running Laravel and installation commands without any issues.

Step # 3 : Install Laravel Breeze for Authentication.

We're using Laravel Breeze because it provides a simple, lightweight authentication system that's easy to customize. This is especially helpful since we’ll be adding a user avatar during the registration process. Run the following command to install Laravel breeze.
composer require Laravel/breeze --dev
This command adds Laravel Breeze to your project using Composer. The --dev flag means it's installed as a development dependency, which is perfect for scaffolding tools like Breeze that you don’t need in production. Next, run the command below to scaffold the authentication system.
php artisan breeze:install
This sets up login, registration, and password reset views along with necessary routes and controllers. You'll also choose a stack (Blade or Inertia) during this step. Now, run the following command to install frontend dependencies and start the dev server.
npm install && npm run dev
This installs JavaScript packages and starts Vite to compile and serve your frontend assets in real-time. In a new terminal, run the following command to prepare your database.
php artisan migrate
This creates the default tables needed for authentication, like users, password_resets, etc.

Step # 4 : Install the Avatar Package.

We’ll use the Laravolt Avatar package to automatically generate user avatars based on their name. Run the following command to install it.
composer require laravolt/avatar
This package generates avatar images based on user names (like JS for John Smith). It supports customization options such as font, size, colors, and shape (circle or square), and can either save the avatars as image files or stream them directly in the browser. It auto-registers, so no manual configuration is required.

Step # 5 : Publish the Configuration File.

Run the following command to publish the config file for the Laravolt Avatar package.
php artisan vendor:publish --provider="Laravolt\Avatar\ServiceProvider"
This command creates a config/avatar.php file, allowing you to customize settings like avatar size, font, colors, and shape according to your needs.

Step # 6 : Create a Storage Link.

Run the following command to create a symbolic link for the storage directory.
php artisan storage:link
This command links the storage/app/public directory to public/storage, making uploaded files (like avatars) accessible via the browser.

Step # 7 : Generate Avatar on User Registration.

We’ll now generate an avatar automatically when a user registers. Update the RegisteredUserController.php file with the following code.
<?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;
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()],
        ]);
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
        Avatar::create($request->name)
        ->setDimension(300, 300) // Set width and height
        ->setFontSize(150) // Set font size for the text
        ->save(storage_path('app/public/avatar_' . $user->id . '.png'));
        event(new Registered($user));
        Auth::login($user);
        return redirect(route('dashboard', absolute: false));
    }
}
This code generates a 300x300 avatar using the user's name and saves it in the storage/app/public/ directory with a filename like avatar_1.png. If you want to keep track of the avatar in your database (for future reference or updates), you can modify the users table by adding a new column (e.g., avatar_filename). After adding this column, ensure it’s marked as fillable in the User model. This way, you can store the avatar’s filename and retrieve it whenever needed, making it easier to update or display the avatar across different parts of your application.

Step # 8 : Display the Avatar.

To show the avatar in the navigation bar, we’ll need to update the navigation view. Open resources/views/layouts/navigation.blade.php and add the following code just before where the username is displayed.
<img src="{{ asset('storage/avatar_' . auth()->id() . '.png') }}" width="30" style="margin-right: 0.25rem">
This code will display the avatar in the navigation bar using the image generated for the logged-in user. It pulls the image from the storage folder and uses the authenticated user's ID to locate their avatar file.

Step # 9 : It's time to test.

Now it’s time to test everything. Start the Laravel development server by running.
php artisan serve
Next, create an account, and after registration, you should see the avatar generated based on the user’s name, appearing in the navigation bar.

Conclusion

By following this guide, you’ve successfully integrated user avatar generation into your Laravel application. Your registration process is now set up to automatically generate personalized avatars based on user names, and these avatars are displayed seamlessly in the navigation bar. This setup provides a customizable and dynamic way to enhance user profiles in your application. With the avatar functionality in place, you can further customize the avatars, adjust their design, or even extend this feature to other user-related areas.
For more details, refer to the official Laravolt Avatar and Laravel 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