How to Upload Avatar in Laravel: A Step-by-Step Guide

How to Upload Avatar in Laravel - A Step-by-Step Guide
Share this:

Hello guys, In this article, I will show you how to upload avatar in Laravel. This is a step-by-step guide that will help you upload an image as an avatar to your Laravel application.

Laravel is a free, open-source PHP web framework. Laravel makes it easy to build Web applications with the best of what PHP has to offer.

Uploading an avatar is a great way to make your profile stand out and make it easier for other members to recognize you.

This tutorial is going to work on any laravel version for eg. laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9.

so, let look into the steps for uploading avatar in laravel.

Steps on How to Upload Avatar in Laravel

  • Step 1: Installing Laravel Application
  • Step 2: Creating Database and Configuration
  • Step 3: Install Auth Scaffolding
  • Step 4: Creating Migration
  • Step 5: Creating Routes
  • Step 6: Creating Controller
  • Step 7: Creating Blade File
  • Step 8: Testing

Step 1: Installing Laravel Application

First, Install laravel application. Run the following command in termial.

composer create-project laravel/laravel avatar-upload
Installing Laravel Application
Installing Laravel Application

After installing laravel application. Run the following command to get into the project directory.

cd avatar-upload

Step 2: Creating Database and Configuration

Now we will create database. Open phpmyadmin and create a new database with name avatar_upload.

Create Database
Create Database

Now configure laravel .env file and enter the database details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=avatar_upload
DB_USERNAME=root
DB_PASSWORD=
Laravel Database Configuration
Laravel Database Configuration

Step 3: Install Auth Scaffolding

Laravel is a PHP framework that provides the ability to create powerful web applications. Laravel has an authentication scaffolding that can be used to create a login form and authenticate users.

This section will cover how to install the Laravel auth scaffolding and use it in your application.

Install Laravel UI using following command

composer require laravel/ui
Installing Laravel UI
Installing Laravel UI

Generating Auth Scaffolding with bootstrap using following command.

php artisan ui bootstrap --auth
Generating Auth Scaffolding with bootstrap
Generating Auth Scaffolding with bootstrap

Please run [npm install && npm run dev] to compile your fresh scaffolding.

npm install 
npm run dev 

Step 4: Creating Migration

Now we are updating a user migration file to add a new field to our user table.

Open user table and add the avatar field to your user table.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('avatar')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};
Adding Avatar Field to User Table
Adding Avatar Field to User Table

Now, run the migration.

php artisan migrate

Update the User.php model file.

app/Models/User.php

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'avatar',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Step 5: Creating Routes

Next step, we are going to create a GET and POST routes for avatar uploading. Update the routes as shown below.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

Route::get('/profile', [App\Http\Controllers\ProfileController::class, 'index'])->name('user.profile');
Route::post('/profile', [App\Http\Controllers\ProfileController::class, 'store'])->name('user.profile.store');
Adding Routes
Adding Routes

Step 6: Creating Controller

We are going to create a Profile Controller in this step with index() and store() methods. Create ProfileController.php and enter the following code inside it.

app/Http/Controllers/ProfileController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class ProfileController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
  
    public function index()
    {
        return view('profile');
    }
  
    public function store(Request $request)
    {
        $request->validate([
            'avatar' => 'required|image',
        ]);
  
        $avatarName = time().'.'.$request->avatar->getClientOriginalExtension();
        $request->avatar->move(public_path('avatars'), $avatarName);
  
        Auth()->user()->update(['avatar'=>$avatarName]);
  
        return back()->with('success', 'Avatar updated successfully.');
    }
}
Creating Profile Controller
Creating Profile Controller

Step 7: Creating Blade File

In this last step, we are creating a blade file form for our profile picture uploading. Create a profile.blade.php and enter the following code inside it.

resources/views/profile.blade.php

@extends('layouts.app')
  
@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Profile') }}</div>
  
                <div class="card-body">
                    <form method="POST" action="{{ route('user.profile.store') }}" enctype="multipart/form-data">
                        @csrf
  
                        @if (session('success'))
                            <div class="alert alert-success" role="alert">
                                {{ session('success') }}
                            </div>
                        @endif
  
                        <div class="row mb-3">
                            <label for="avatar" class="col-md-4 col-form-label text-md-end">{{ __('Avatar') }}</label>
  
                            <div class="col-md-6">
                                <input id="avatar" type="file" class="form-control @error('avatar') is-invalid @enderror" name="avatar" value="{{ old('avatar') }}" required autocomplete="avatar">
  
                                <img src="/avatars/{{ Auth::user()->avatar }}" style="width:80px;margin-top: 10px;">
  
                                @error('avatar')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
  
                        <div class="row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-dark">
                                    {{ __('Upload Profile') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
Profile Blade File
Profile Blade File

Now update the app.blade.php file to add upload avatar button and displaying avatar image into navigation bar.

resources/views/layouts/app.blade.php

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>How to Upload Avatar in Laravel: A Step-by-Step Guide - LaravelTuts.com</title>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.bunny.net/css?family=Nunito" rel="stylesheet">

    <!-- Scripts -->
    @vite(['resources/sass/app.scss', 'resources/js/app.js'])
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    How to Upload Avatar in Laravel: A Step-by-Step Guide - LaravelTuts.com
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav me-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ms-auto">
                        <!-- Authentication Links -->
                        @guest
                            @if (Route::has('login'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                                </li>
                            @endif

                            @if (Route::has('register'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                </li>
                            @endif
                        @else
                            <li class="nav-item my-auto mx-2">
                                <a class="btn btn-dark " href="/profile" >
                                    Upload Avatar
                                </a>
                            </li>
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    <img src="/avatars/{{ Auth::user()->avatar }}" style="width: 30px; border-radius: 10%">
                                    {{ Auth::user()->name }}
                                </a>
                                <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>
</html>

Step 8: Testing

That its. Everything is done now we can test our laravel application. Run the laravel serve command.

php artisan serve

and also run VITE for our application to to compile your fresh css and js.

For Development Run:

npm run dev

For Production Run:

npm run build

Now open the following link in any web browser and register for new user. And now you can upload you first avatar.

http://127.0.0.1:8000/

Previews:

Register New User

After registration you are redirected to dashboard. Click the Upload Avatar from navigation and upload a new avatar.

Upload New Avatar
Upload New Avatar

Conclusion

This concludes our tutorial on how to upload an avatar in Laravel. We hope you found it helpful. If you did, please like and share this article, and leave us a comment to let us know what you think. If you like the tutorial please subscribe our youtube channel and follow us on social network facebook and instagram.

Download

Share this:

Leave a Reply