How to Generate Avatar Image for User in Laravel?

By Hardik Savani December 13, 2024 Category : Laravel

In this post, I will show you how to create dynamic user avatar in laravel application.

User avatars are a great way to add a personal touch to user profiles in web applications. In this tutorial, we'll demonstrate how to generate dynamic image avatars in Laravel using the first two letters of a user's name. To achieve this, we'll utilize the laravolt/avatar composer package to create custom avatar images in a Laravel application.

Let's follow the steps to do the examples:

Step 1: Install Laravel

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Install laravolt/avatar

Now, in this step, we will install laravolt/avatar composer package. So, run the following command:

composer require laravolt/avatar

Step 3: Setup Avatar

Here, we will display dynamic user avatar using the following method:

Avatar::create('Hardik Savani')->toSvg();

You can see the full user list like the following way:

resources/views/users/index.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container">
    <div class="card mt-5">
        <div class="card-header"><h4>User List</h4></div>
        <div class="card-body" id="table-data">
            
            <table class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($users as $user)
                    <tr>
                        <td>{{ $user->id }}</td>
                        <td>{!! Avatar::create($user->name)->setDimension(35, 35)->setFontSize(15)->toSvg() !!} {{ $user->name }}</td>
                        <td>{{ $user->email }}</td>
                    </tr>
                    @endforeach
                </tbody>
            </table>

            {{ $users->links("pagination::bootstrap-5") }}

        </div>
    </div>
</div>

</body>
</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/users

You can see the output:

Output:

I hope it can help you...

Tags :
Shares