laravelでユーザー管理

管理者、閲覧者など、権限によって、閲覧、編集を制限したり、表示するページを出し分けたい。

ということだが、ドキュメントを全部見ろ、とのこと。
http://laravel.jp/

tinymceの機能を考えてた時も、「ドキュメント全部読め」って怒られたけど、どうやらドキュメント読むのは基本のようね。ということで、laravelのドキュメントを読み進めたいと思います。

laravelを作っていく

frontが出来たので、
[vagrant@localhost local]$ php -v
PHP 7.1.21 (cli) (built: Aug 15 2018 18:11:46) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies

ディレクトリにcomposerが入っているので、
php composer.phar create-project –prefer-dist laravel/laravel zeus

出来ました。
[vagrant@localhost local]$ cd zeus
[vagrant@localhost zeus]$ ls
app composer.json database public routes tests
artisan composer.lock package.json readme.md server.php vendor
bootstrap config phpunit.xml resources storage webpack.mix.js

laravelのロギング

ログの設定ファイルは config/logging.php
なるほど、設定ファイル系はconfig配下にありますな。

syslog, slackなどにログ出力ができる。syslogってなんだ?

'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['single'],
        ],

        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
        ],

        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'days' => 7,
        ],

        'slack' => [
            'driver' => 'slack',
            'url' => env('LOG_SLACK_WEBHOOK_URL'),
            'username' => 'Laravel Log',
            'emoji' => ':boom:',
            'level' => 'critical',
        ],

        'stderr' => [
            'driver' => 'monolog',
            'handler' => StreamHandler::class,
            'with' => [
                'stream' => 'php://stderr',
            ],
        ],

        'syslog' => [
            'driver' => 'syslog',
            'level' => 'debug',
        ],

        'errorlog' => [
            'driver' => 'errorlog',
            'level' => 'debug',
        ],
    ],

Syslog は、ログメッセージをIPネットワーク上で転送するための標準規格である。” Syslog” という用語は、その通信プロトコルを指すだけでなく、Syslog メッセージを送信するアプリケーションやライブラリに対しても使われる

とりあえず、slackに通知したいですね。あああああああ、全然追いつかねーな。むしろ離されている感が強い。。

エラー時に表示するページのカスタマイズ

/app/Exceptions/Handler.phpを編集する

Handler.phpの最下部

public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }

以下に変える。$e->getStatusCodeで判定する。
view(‘errors.403’)が上手くいかない

public function render($request, Exception $e){
        if($this->isHttpException($e)){
            if($e->getStatusCode() == 403){
                return response()->view('errors.403');
            }

            if($e->getStatusCode() == 404){
                return response()->view('errors.404');
            }
            return response()->view('errors.500')

        }

        return parent::render($request, $e);
    }

laravel5.2だからか。そりゃそうだ。

public function report(Exception $e)でレポートメールの送信もできるっぽい。。

laravel エラーハンドリング

config/app.php設定ファイルのdebug設定オプションで決定

これか?

'debug' => env('APP_DEBUG', false),

実働環境でこの値をtrueにしてしまうと、アプリケーションのエンドユーザーへ、セキュリティリスクになりえる設定情報を表示する

例えば、falseでcontroller未設定のページのリクエストをすると、

404が表示されます。

trueにします。
あれ、404のままだ。ん?404は404か。

システムエラー時は500のページ
存在しないURLにアクセスされた時は404のページ

laravelのキャッシュクリアコマンド

まず、サーバーを起動します。
[vagrant@localhost laravel]$ php artisan serve –host=192.168.35.10 –port=8000
Laravel development server started:
[Wed Oct 10 22:07:11 2018] 192.168.35.1:56161 [200]: /js/main.js
[Wed Oct 10 22:07:11 2018] 192.168.35.1:56160 [200]: /css/styles.css
[Wed Oct 10 22:07:14 2018] 192.168.35.1:56166 [200]: /favicon.ico
[Wed Oct 10 22:07:17 2018] 192.168.35.1:56168 [200]: /css/styles.css
[Wed Oct 10 22:07:17 2018] 192.168.35.1:56172 [200]: /favicon.ico

[vagrant@localhost laravel]$ php artisan cache:clear
Failed to clear cache. Make sure you have the appropriate permissions.

あれ?
git hub issueに上がってますね。
https://github.com/laravel/framework/issues/25451#issuecomment-424743418

ディレクトリを作成します。

Wow! すげ!
[vagrant@localhost laravel]$ php artisan cache:clear
Application cache cleared!

application以外でも、configuration, route, compiled viewもclearできます。
[vagrant@localhost laravel]$ php artisan config:clear
Configuration cache cleared!
[vagrant@localhost laravel]$ php artisan route:clear
Route cache cleared!
[vagrant@localhost laravel]$ php artisan view:clear
Compiled views cleared!

ドキュメントも読んでおきましょう。
https://readouble.com/laravel/5.6/ja/cache.html
redis, memcacheにも対応しているようです。

make:auth 認証時のエラー処理

resources/lang/en/passwords.phpを変更する。

‘failed’ => ‘These credentials do not match our records.’,
‘throttle’ => ‘Too many login attempts. Please try again in :seconds seconds.’,

目算間違えた。。結構やらなきゃいけない量が大量にあるな。

make:auth後のルーティング

[vagrant@localhost demo]$ php artisan route:list
+——–+———-+————————+——————+————————————————————————+————–+
| Domain | Method | URI | Name | Action | Middleware |
+——–+———-+————————+——————+————————————————————————+————–+
| | GET|HEAD | / | | Closure | web |
| | GET|HEAD | api/user | | Closure | api,auth:api |
| | GET|HEAD | home | home | App\Http\Controllers\HomeController@index | web,auth |
| | GET|HEAD | login | login | App\Http\Controllers\Auth\LoginController@showLoginForm | web,guest |
| | POST | login | | App\Http\Controllers\Auth\LoginController@login | web,guest |
| | POST | logout | logout | App\Http\Controllers\Auth\LoginController@logout | web |
| | POST | password/email | password.email | App\Http\Controllers\Auth\ForgotPasswordController@sendResetLinkEmail | web,guest |
| | GET|HEAD | password/reset | password.request | App\Http\Controllers\Auth\ForgotPasswordController@showLinkRequestForm | web,guest |
| | POST | password/reset | password.update | App\Http\Controllers\Auth\ResetPasswordController@reset | web,guest |
| | GET|HEAD | password/reset/{token} | password.reset | App\Http\Controllers\Auth\ResetPasswordController@showResetForm | web,guest |
| | GET|HEAD | register | register | App\Http\Controllers\Auth\RegisterController@showRegistrationForm | web,guest |
| | POST | register | | App\Http\Controllers\Auth\RegisterController@register | web,guest |
+——–+———-+————————+——————+————————————————————————+————–+

/home はログイン後の画面

routes/web.php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

resources/views/authに以下のphpファイルが出来ている
– login.blade.php
– register.blade.php
– verify.blade.php
– passwords/email.blade.php
– passwords/reset.blade.php

また、views/layouts/app.blade.php もできている。

app/Http/controllers/Auth にcontrollerもできている。
ForgotPasswordController.php
LoginController.php
RegisterController.php
ResetPasswordController.php
VertificationController.php

database/migration
users_table.php, password_resets_table.php

LoginController、RegisterController、ResetPasswordControllerのリダイレクト先を変更する。デフォルトはhome

protected $redirectTo = '/';

laravelでログイン機能を作ろう

composerをインストールした後に、laravelを入れます。
そうですね、project nameはdemoあたりにしておきましょう。

$ php composer.phar create-project –prefer-dist laravel/laravel demo
Installing laravel/laravel (v5.7.0)

続いてDBをつくる
mysql> create database demo;

DBを設定していく
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=hoge
DB_USERNAME=hoge
DB_PASSWORD=hoge

[vagrant@localhost demo]$ php artisan make:auth
Authentication scaffolding generated successfully.

あれ? なんじゃこりゃ?
[vagrant@localhost demo]$ php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table

[vagrant@localhost demo]$ php artisan serve –host=192.168.35.10 –port=8000
Laravel development server started:

mysql> use demo
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+—————-+
| Tables_in_demo |
+—————-+
| migrations |
| users |
+—————-+
2 rows in set (0.00 sec)

mysql> describe users;
+——————-+——————+——+—–+———+—————-+
| Field | Type | Null | Key | Default | Extra |
+——————-+——————+——+—–+———+—————-+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| email | varchar(255) | NO | | NULL | |
| email_verified_at | timestamp | YES | | NULL | |
| password | varchar(255) | NO | | NULL | |
| remember_token | varchar(100) | YES | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+——————-+——————+——+—–+———+—————-+
8 rows in set (0.11 sec)

なんじゃこりゃーーーーーーーーーーーーーーーーーーーーーー??
えええ?
意味が分からん。。
認証機能ね。

/config/auth.php

password_reset tableがないな。。

php artisan serve –host 192.168.35.10 –port 8000

Too many arguments, expected arguments “command”.

ん?

[vagrant@localhost laravel]$ php artisan serve -host=192.168.35.10 -port=8000
Description:
Serve the application on the PHP development server

Usage:
serve [options]

Options:
–host[=HOST] The host address to serve the application on [default: “127.0.0.1”]
–port[=PORT] The port to serve the application on [default: 8000]
-h, –help Display this help message
-q, –quiet Do not output any message
-V, –version Display this application version
–ansi Force ANSI output
–no-ansi Disable ANSI output
-n, –no-interaction Do not ask any interactive question
–env[=ENV] The environment the command should run under
-v|vv|vvv, –verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

hostは –hostですな。

修正しました。
[vagrant@localhost laravel]$ php artisan serve –host=192.168.35.10 –port=8000

さて、まずやっていくのは
1. ログイン機能
2. テーブル作成

このあたりか。
ログインはいきなり実装するのは怖い。