Home Laravel How to Upload Profile Photo in Laravel?

How to Upload Profile Photo in Laravel?

by Shahriar Sagor

Hello Dev’s , today here, I will show you how to upload a profile photo in laravel application. I will show this example step by step with explains laravel and how to upload a profile images in our laravel application. if we want to see an example of a laravel profile image upload then i hope you are in the right place. Now I will explained this simply how to upload a profile photo avatar in laravel application. Here, i will be Creating a basic example of a laravel profile picture upload.

Now in this post, I will be show you step-by-step how to create a profile page for profile image upload. Here i will create basic auth by using laravel ui. Then i will add an avatar column to the user’s table for profile pictures. Now i will create one GET route to show the profile page with the form. Then the user can upload or change their profile photo from that page. Then i will create a POST route to submit the form.

so, let’s follow the below steps:

We can also use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.

Step 1: Install Laravel

This is optional; however, if we have not created the laravel application, then we may go ahead and then execute the below command:

composer create-project laravel/laravel example-app

Step 2: Setup Database Configuration

After the successfully installing the laravel application then need to configuring the database setup. Now i will open the “.env” file and then change the database name, username and password in the env file.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

Step 3: Install Auth Scaffold

We know that Laravel’s is provide us laravel/ui package for a quick way to scaffold all of the routes and also views we need for authentication by using a few simple commands:

composer require laravel/ui

Next, i have to generate auth scaffold with the bootstrap, so let’s run the below command:

php artisan ui bootstrap --auth

Then, need to install npm packages by using the below command:

npm install

At last, need to built bootstrap CSS by using the below command:

npm run build

Step 4: Create Migration

Now in this step, i have to create a new migration to add the avatar field to the users table. so just let’s run the below code and run migration.

php artisan make:migration add_new_fields_users

database/migrations/2022_11_24_110854_add_new_fields_users.php

<?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::table('users', function (Blueprint $table) {
            $table->string('avatar')->nullable();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('avatar');
        });
    }

};

Now, run just migration with the following command:

php artisan migrate

Next, just update the User.php model file.

app/Models/User.php

<?php
    
namespace App\Models;
    
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

     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'avatar',
    ];
  
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array

     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
  
    /**
     * The attributes that should be cast.
     *
     * @var array

     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

}

Step 5: Create Route

Now in this step, i will create profile GET and POST routes for profile image upload. We can see this in the below routes:

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');

Step 6: Create Controller

Here, i will be create ProfileController with index() and store() method. so let’s copy the below code and then add it to the controller file:

app/Http/Controllers/ProfileController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class ProfileController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
  
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('profile');
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    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.');
    }
}

Step 7: Create Blade File

Now In this step, i will create a profile blade file. So in this file, i will add a form for profile picture upload. so let’s just update the following file:

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-primary">
                                    {{ __('Upload Profile') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Next, Add the Profile Page link and avatar on the top navbar as like as below:

resources/views/layouts/app.blade.php
...
  

<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 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 href="{{ route('user.profile') }}" class="dropdown-item">Profile</a>
            <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>
  
...

Read Also: How to Take Website Screenshot From URL in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like