Reference:https://devdojo.com/episode/laravel-user-image
Auth Template
php artisan make:auth
Test
Add avatar column
create_users_table.php1
| $table->string('avatar')->default('default.jpg');
|
php artisan migrate
Profile link
resources/views/layouts/app.blade.php1 2 3 4 5
| <li> <a href="{{ url('/profile') }}"> <i class="fa fa-btn fa-user"></i>Profile </a> </li>
|
routes.php1
| Route::get('profile', 'UserController@profile');
|
UserController.php1 2 3 4 5
| use Auth; public function profile(){ return view('profile', array('user' => Auth::user()) ); }
|
profile.blade.php1 2 3 4 5 6 7 8 9 10 11 12
| @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <h2>{{ $user->name }}'s Profile</h2> </div> </div> </div> @endsection
|
Test
Default Image
profile.blade.php1
| <img src="/uploads/avatars/{{ $user->avatar }}" style="width:150px; height:150px; float:left; border-radius:50%; margin-right:25px;"
|
Test
Upload table
profile.blade.php1 2 3 4 5 6
| <form enctype="multipart/form-data" action="/profile" method="POST"> {{ csrf_field() }} <label>Update Profile Image</label> <input type="file" name="avatar"> <input type="submit" class="pull-right btn btn-sm btn-primary"> </form>
|
routes.php1
| Route::post('profile', 'UserController@update_avatar');
|
UserController.php1 2 3
| public function update_avatar(Request $request){ // Handle the user upload of avatar }
|
Install Intervention Image Package
http://image.intervention.io/
composer require intervention/image
config/app.php1 2 3 4
| ... Intervention\Image\ImageServiceProvider::class, ... 'Image' => Intervention\Image\Facades\Image::class,
|
Upload Success!
UserController.php1 2 3 4 5 6 7 8 9 10 11 12 13
| use Image; public function update_avatar(Request $request){ // Handle the 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()) ); }
|
Test
User Navbar Image
resources/views/layouts/app.blade.php1 2
| <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" style="position:relative; padding-left:50px;"> <img src="/uploads/avatars/{{ Auth::user()->avatar }}" style="width:32px; height:32px; position:absolute; top:10px; left:10px; border-radius:50%">
|