1. 라이브러리리 설치
1 | composer create-project laravel/laravel LaravelImageUpload | cs |
1 | php artisan make:auth | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 | public function up() { Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('email')->unique(); $table->string('profile_image')->nullable(); //프로필 이미지 필드 $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } | cs |
5. 마이그레이션 해준다.
1 | php artisan migrate | cs |
6. app/User.phpd 에 fillable 추가 'profile_image'
1 2 3 | protected $fillable = [ 'name', 'email', 'password', 'profile_image' ]; | cs |
7. User.php 에 아래의 소스를 추가한다. auth()->user()->image 사용하는 대신 새 접근 자 메서드를 추가 profile_image
1 2 3 4 | public function getImageAttribute() { return $this->profile_image; } | cs |
8. web.php 파일을 연다. 새 페이지 설정을 위해 web.php에 route를 작성한다.
1 2 | Route::get('/profile', 'ProfileController@index')->name('profile'); Route::post('/profile/update', 'ProfileController@updateProfile')->name('profile.update'); | cs |
9. 컨트롤러를 작성하자
1 | php artisan make:controller ProfileController |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ProfileController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { return view('auth.profile'); } } | cs |
11. resources/view/auth/profie.blade.php 이미지 업로드 양식을 만들어주자
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | @extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-12"> <div class="card"> <div class="card-header">Profile</div> <div class="card-body"> @if (session('status')) <div class="alert alert-success" role="alert"> {{ session('status') }} </div> @endif <div class="container"> <div class="row"> <div class="col-12"> @if ($errors->any()) <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <ul> @foreach ($errors->all() as $error) <li> {{ $error }} </li> @endforeach </ul> </div> @endif <form action="{{ route('profile.update') }}" method="POST" role="form" enctype="multipart/form-data"> @csrf <div class="form-group row"> <label for="name" class="col-md-4 col-form-label text-md-right">Name</label> <div class="col-md-6"> <input id="name" type="text" class="form-control" name="name" value="{{ old('name', auth()->user()->name) }}"> </div> </div> <div class="form-group row"> <label for="email" class="col-md-4 col-form-label text-md-right">Email</label> <div class="col-md-6"> <input id="email" type="text" class="form-control" name="email" value="{{ old('email', auth()->user()->email) }}" disabled> </div> </div> <div class="form-group row"> <label for="profile_image" class="col-md-4 col-form-label text-md-right">Profile Image</label> <div class="col-md-6"> <input id="profile_image" type="file" class="form-control" name="profile_image"> @if (auth()->user()->image) <code>{{ auth()->user()->image }}</code> @endif </div> </div> <div class="form-group row mb-0 mt-5"> <div class="col-md-8 offset-md-4"> <button type="submit" class="btn btn-primary">Update Profile</button> </div> </div> </form> </div> </div> </div> </div> </div> </div> </div> </div> @endsection | cs |
12. <a class="dropdown-item" href="{{ route('profile') }}">Profile</a> 이 소스를 로그아웃 전에 삽입해준다.
1 2 3 4 5 6 7 8 9 10 11 12 | <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> {{ __('Logout') }} </a> <a class="dropdown-item" href="{{ route('profile') }}">Profile</a> <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> @csrf </form> | cs |
13. 이제 프로필 링크를 클릭 하면 아래 처럼 보인다.
14. 뷰 템플릿 수정을 마친 후 이미지를 업로드 할 파일 시스템을 구성해야한다. config/filesystem.php 파일로 이동하여 public 아래의 디스크 설정을 변경하자.
1 2 3 4 5 6 | 'public' => [ 'driver' => 'local', 'root' => public_path(), 'url' => env('APP_URL').'/public', 'visibility' => 'public', ], | cs |
15. app아래에 Traits 폴더를 생성해주자
16. Traits 폴더 아래에 UploadTrait.php 라는 파일을 추가하자.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php namespace App\Traits; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; trait UploadTrait { public function uploadOne(UploadedFile $uploadedFile, $folder = null, $disk = 'public', $filename = null) { $name = !is_null($filename) ? $filename : str_random(25); $file = $uploadedFile->storeAs($folder, $name.'.'.$uploadedFile->getClientOriginalExtension(), $disk); return $file; } } | cs |
17. ProfileController을 아래의 코드로 수정해준다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | <?php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; use App\Traits\UploadTrait; class ProfileController extends Controller { use UploadTrait; public function __construct() { $this->middleware('auth'); } public function index() { return view('auth.profile'); } public function updateProfile(Request $request) { // Form validation $request->validate([ 'name' => 'required', 'profile_image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048' ]); // Get current user $user = User::findOrFail(auth()->user()->id); // Set user name $user->name = $request->input('name'); // Check if a profile image has been uploaded if ($request->has('profile_image')) { // Get image file $image = $request->file('profile_image'); // Make a image name based on user name and current timestamp $name = str_slug($request->input('name')).'_'.time(); // Define folder path $folder = '/uploads/images/'; // Make a file path where image will be stored [ folder path + file name + file extension] $filePath = $folder . $name. '.' . $image->getClientOriginalExtension(); // Upload image $this->uploadOne($image, $folder, 'public', $name); // Set user profile image path in database to filePath $user->profile_image = $filePath; } // Persist user record to database $user->save(); // Return user back and show a flash message return redirect()->back()->with(['status' => 'Profile updated successfully.']); } } | cs |
18. app.blade.php 파일에서 아래의 부분을 (프로필 사진 불러오기)
1 2 3 | <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre> {{ Auth::user()->name }} <span class="caret"></span> </a> | cs |
이렇게 수정해준다.
1 2 3 4 5 6 | <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre> @if (auth()->user()->image) <img src="{{ asset(auth()->user()->image) }}" style="width: 40px; height: 40px; border-radius: 50%;"> @endif {{ Auth::user()->name }} <span class="caret"></span> </a> | cs |
19. 기능 작동이 잘된다.
public 디렉토리로 변경하고 싶을경우
config/filesystem.php 파일을 변경한다.
아래와 같이 권한줄것
4.1 chmod -R 777 public
'라라벨 > 라이브러리' 카테고리의 다른 글
라라벨 마크다운 문서작성 라이브러리 (0) | 2020.12.26 |
---|---|
디버그바 설치 (0) | 2020.03.04 |
excel export 쿼리문으로 엑셀 추출 (0) | 2020.01.22 |
laravel log-viewer 설치 (0) | 2019.08.31 |
laravel sweet-alert 설치 경고창 설정 (0) | 2019.08.30 |