Laravel 5.5 Upload User Image with example.




Hello Shouters,

This is Krishna Gupta from Technology shouters. here with an another great useful article So, today I am going to tell you that how we can upload an image in laravel 5.5(Latest Version released in August 2017).

Check out the new features of Laravel 5.5

As everybody knows that how popular & strong laravel is. As we can observe as per version updated there is so many changes we can see in the laravel’s folder structure. you can now easily work with the validation also in images dimensions.

Why we use laravel Framework.?

Laravel is the first choice of Brilliant programmers nowadays why so it? the reason is very simple.
as everyone knows how Strong laravel for Big projects and how secure it is.Also, laravel provides many pre-installed libraries for to do difficult tasks in an easy manner. rather than the other frameworks like Zend, CakePHP & Yii.

So Here we go and understand how easily we can be done image upload with laravel

#1:-If you are Beginner so let’s start to do this. first Install the laravel fresh installation on your local server/ live server. If you don’t know how to do that. then don’t worry you can find here everything.

How to install and Configure Laravel 5.5 on ubuntu

#2:-Now you need to make an authentication system. Do you think how easy it is?
Open your terminal and write only this single command and hit enter.


php artisan make:auth

This single command will install all required files like controllers, models and views that essential for a user authentication system.

#3.After Setup an authentication system you required to do some changes in files for Build an image uploading system.

Now you need to Add the image/avatar field to the ‘create_users_table’ migration file.you can find this file in Database -> Migrations Directory.

You need to add this line inside your up function


 $table->string('avatar')->default('user.jpg');

So you will see after changes file will look like this.


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

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

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }
}

#4. Make sure your Database connectivity is perfect. because now migration mandatory to apply for reflect the chnages. you can check your DB connection inside .env file.

#5. Open your terminal write the migration command to migrate all new changes to the Database table.


php artisan migrate

#6. Open resources/views/layouts/app.blade.php file to add profile & Logout buttons.


<ul class="dropdown-menu" role="menu">
    <li><a href="{{ url('/profile') }}">User Profile</a></li>
    <li><a href="{{ url('/logout') }}">Logout</a></li>
</ul>

#7. Setup your route GET method in web.php file.


Route::get('profile', 'UserController@profile');
Route::post('profile', 'UserController@update_avatar');

#8. Create new Controller called UserController.php and add the follwing code to setup the profile method.


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use Image;
use Auth;

class UserController extends Controller
{
    public function profile(){
    	return view('profile', array('user' => Auth::user()) );
    }
}

#9.Create the new view file called profile.blade.php inside resources/views/ Directory.

Add the following code snippets inside the file.


@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <img src="/uploads/avatars/{{ $user->avatar }}" style="width:150px; height:150px; float:left; border-radius:50%; margin-right:25px;">
            <h2>{{ $user->name }}'s Profile</h2>
            <form enctype="multipart/form-data" action="/profile" method="POST">
                <label>Update Profile Image</label>
                <input type="file" name="avatar">
                <input type="hidden" name="_token" value="{{ csrf_token() }}">
                <input type="submit" class="pull-right btn btn-sm btn-primary">
            </form>
        </div>
    </div>
</div>
@endsection

#10.Now need to Install Image Intervention Packages inside the laravel project you can find here http://image.intervention.io/

#11.Create the update_avatar method inside the UserController.php Controller.

So final UserController.php file will look like this.


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
use Image;

class UserController extends Controller
{
    public function profile(){
    	return view('profile', array('user' => Auth::user()) );
    }

    public function update_avatar(Request $request){

    	// Logic for user upload of avatar
    	if($request->hasFile('avatar')){
    		$avatar = $request->file('avatar');
    		$filename = time() . '.' . $avatar->getClientOriginalExtension();
    		Image::make($avatar)->resize(300, 300)->save( public_path('/uploads/avatars/' . $filename ) );

    		$user = Auth::user();
    		$user->avatar = $filename;
    		$user->save();
    	}

    	return view('profile', array('user' => Auth::user()) );

    }
}


#12. Add the user profile image to the following code inside of resources/views/layouts/app.blade.php.


<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
    <img src="/uploads/avatars/{{ Auth::user()->avatar }}" style="width:32px; height:32px; position:absolute; top:10px; left:10px; border-radius:50%">
    {{ Auth::user()->name }} <span class="user_img"></span>
</a>

OUTPUT:

Technology Shouters - User profile picture upload in laravel

That’s it. Facing any problem to setup application? Please feel free to leave the comments below. you can easily download Complete Source code from GitHub.

Download Source code from Github

Krishna Gupta

Krishna Ballabh Gupta is a Gold Medalist Full Stack Developer & Algorithm Designer and Founder of TechnologyShouters. He generally Blogs about Python, JavaScript, jQuery, AngularJS, Database, PHP, AJAX and something that interesting.

Related Posts

Create Account



Log In Your Account



1Subscribe to Our Live Updates.