LoginSignup
20

More than 3 years have passed since last update.

【Laravel】メアド以外でログインしたい

Last updated at Posted at 2018-02-06

標準の

$ php artisan make:auth

でログインを作るとメアドとパスワードでログインするようになる。
メアドではなく name でログインする方法
LoginController に以下の関数を追加する。別のフィールドをログインに使う場合はそのフィールド名を記述

app/Http/Controllers/Auth/LoginController.php

+    public function username()
+    {
+        return 'name';
+    }

ログイン画面をカスタマイズする。
resources/views/auth/login.blade.php

-                        <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
-                            <label for="email" class="col-md-4 control-label">メールアドレス</label>
-
-                            <div class="col-md-6">
-                                <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
-
-                                @if ($errors->has('email'))
-                                    <span class="help-block">
-                                        <strong>{{ $errors->first('email') }}</strong>
-                                    </span>
-                                @endif
-                            </div>
-                        </div>
+                        <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
+                            <label for="name" class="col-md-4 control-label">名前</label>
+
+                            <div class="col-md-6">
+                                <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>
+
+                                @if ($errors->has('name'))
+                                    <span class="help-block">
+                                        <strong>{{ $errors->first('name') }}</strong>
+                                    </span>
+                                @endif
+                            </div>
+                        </div>

この他にもユーザー名が重複しないようバリデーションチェックを入れるとかの対応は必要だが、とりあえずこれで name でログインが可能になる。

usersテーブルのemailフィールド同様、nameフィールドも unique にしておいた方が良いかもね。

- 目次 -

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20