Skip to content

Instantly share code, notes, and snippets.

@shrek-kurata
Created June 24, 2018 08:10
Show Gist options
  • Save shrek-kurata/1441fe4de90e598981e01f3ee7e7c88a to your computer and use it in GitHub Desktop.
Save shrek-kurata/1441fe4de90e598981e01f3ee7e7c88a to your computer and use it in GitHub Desktop.
Laravelで 画像リサイズと画像保存を簡易にできる方法 ref: https://qiita.com/ryuseikurata/items/3ba472e933f2f5bfe043
<?php
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('default.jpg');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
<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%">
{{ Auth::user()->name }} <span class="caret"></span>
</a>
php artisan make:auth
$table->string('avatar')->default('default.jpg');
DB_DATABASE=(自分のデータベースの名前)
DB_USERNAME=(データベースに入るためのユーザの名前)
#DB_PASSWORD=secret(ローカル開発環境ならば、パスワードを設定しなくても大丈夫だと思います)
php artisan migrate:refresh
@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
<?php
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){
// 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()) );
}
}
Route::post('profile', 'UserController@update_avatar');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment