Laravel5.6 Separate user and administrator authentication, leaving only administrator credentials with name and password only

Sep 3, 2020 PHP beginners Laravel for beginners laravel 5.6

Purpose

Implementation environment

Items Information
OS macOS Catalina (10.15.5)
PC MacBook Pro (13-inch, 2020, Four Thunderbolt 3 ports)
Processor 2 GHz Quad Core Intel Core i5
Memory 32 GB 3733 MHz LPDDR4
Graphics Intel Iris Plus Graphics 1536 MB
Items Information Remarks
PHP version 7.4.3 Introduced with Homwbrew
Laravel version 5.6.40 Introduced by this method using commposer → Build Mac Laravel environment
MySQL version 8.0.19 for osx10.13 on x86_64 Install using this method using Homwbrew → Install MySQL with Mac Homebrew

Prerequisites

――The environment is close to the previous implementation environment.

Prerequisite information

Feeling after reading

Overview

  1. Creating a database
  2. Create and initialize Laravel app
  3. Create user authentication function
  4. Preparation of table for administrator information
  5. Add guards and providers
  6. Controller modification
  7. Creating an authentication page
  8. Creating a transition page after authentication
  9. Description of routing, setting of transition page after authentication, and description of processing at exception
  10. Confirmation

#Details

  1. Creating a database

    1. Execute the following command to log in to MySQL from the terminal. (If you have forgotten the password of the MySQL root user, click here → How to reset when you forget the root password of MySQL 8.x in Mac local environment)

      $ mysql -u root -p
      
    2. Execute the following SQL to create a “multi_auth” database.

      create database multi_auth_info_limited;
      
    3. Execute the following SQL to output the database list and check that “multi_auth_info_limited” is included. After confirmation, log out of MySQL.

      show databases;
      
  2. Create and initialize Laravel app

    1. Move to any directory where you want to create the Laravel app.

    2. Execute the following command to create a Laravel 5.6 application called “multi_auth_info_limited”. (It may take some time to complete, so wait for a while.)

      $ composer create-project laravel / laravel multi_auth_info_limited "5.6. *"
      
    3. Execute the following command to move to the created application name directory. Subsequent commands shall be executed inside this multi_auth directory unless otherwise specified.

      $ cd multi_auth_info_limited
      
    4. Execute the following command to open the .env file.

      $ vi .env
      
    5. Modify the database description in the .env file as shown below.

      DB_DATABASE = multi_auth_info_limited
      DB_USERNAME = root
      DB_PASSWORD = mysql -u password entered when executing the root -p command
      
    6. Describe the entire contents of the modified .env file.

      APP_NAME = Laravel
      APP_ENV = local
      APP_KEY = The description of the app key is different for each individual.
      APP_DEBUG = true
      APP_URL = http: // localhost
             
      LOG_CHANNEL = stack
             
      DB_CONNECTION = mysql
      DB_HOST = 127.0.0.1
      DB_PORT = 3306
      DB_DATABASE = multi_auth_info_limited
      DB_USERNAME = root
      DB_PASSWORD = Password for the MySQL root user in your environment
             
      BROADCAST_DRIVER = log
      CACHE_DRIVER = file
      QUEUE_CONNECTION = sync
      SESSION_DRIVER = file
      SESSION_LIFETIME = 120
             
      REDIS_HOST = 127.0.0.1
      REDIS_PASSWORD = null
      REDIS_PORT = 6379
             
      MAIL_MAILER = smtp
      MAIL_HOST = smtp.mailtrap.io
      MAIL_PORT = 2525
      MAIL_USERNAME = null
      MAIL_PASSWORD = null
      MAIL_ENCRYPTION = null
      MAIL_FROM_ADDRESS = null
      MAIL_FROM_NAME = "$ {APP_NAME}"
             
      AWS_ACCESS_KEY_ID =
      AWS_SECRET_ACCESS_KEY =
      AWS_DEFAULT_REGION = us-east-1
      AWS_BUCKET =
             
      PUSHER_APP_ID =
      PUSHER_APP_KEY =
      PUSHER_APP_SECRET =
      PUSHER_APP_CLUSTER = mt1
             
      MIX_PUSHER_APP_KEY = "$ {PUSHER_APP_KEY}"
      MIX_PUSHER_APP_CLUSTER = "$ {PUSHER_APP_CLUSTER}"
      
    7. Execute the following command to migrate the initial migration file.

      $ php artisan migrate
      
    8. Execute the following command to start the local server.

      $ php artisan serve
      
    9. Access the following and confirm that the initial screen of Laravel is displayed. -http://localhost:8000/

       ![Laravel-4.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/306417/ca4135f5-c29f-69ba-bed7-01d9735a683b.png)
      
  3. Create user authentication function

    1. Execute the following command to create a user authentication function.

      $ php artisan make: auth
      
    2. Execute the following command to start the local server.

      $ php artisan serve
      
    3. Access the following to open the initial screen of Laravel. -http://localhost:8000/

       ![Laravel.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/306417/4e37a799-774a-1d25-3c8f-4dfb9a8929e6.png)
      
    4. Click “REGISTER” on the upper right.Laravel.png

    5. Enter various information and click “Register”.

      Laravel-2.png

    6. Click “Register” and confirm that the screen changes to the dorsal horn screen.

      Laravel-3.png![Laravel-3.png]!.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/306417/6aefa2ea-9b95-ff79-484f-aedf92de18a0.png)

  4. Preparation of table for administrator information

    1. Execute the following command to create the Admin model file and the migration file for creating the admins table.

      $ php artisan make: model Admin -m
      
    2. Execute the following command to open the migration file created earlier. (The part of YYYY_MM_DD_XXXXXX differs depending on the migration file creation date.)

      $ vi database / migrations / YYYY_MM_DD_XXXXXX_create_admins_table.php
      
    3. Add the opened migration file as follows.

      <? php
             
      use Illuminate \ Support \ Facades \ Schema;
      use Illuminate \ Database \ Schema \ Blueprint;
      use Illuminate \ Database \ Migrations \ Migration;
             
      class CreateAdminsTable extends Migration
      {
          / **
           * Run the migrations.
           *
           * @return void
           * /
          public function up ()
          {
              Schema :: create ('admins', function (Blueprint $ table) {
                  $ table-> increments ('id');
                  // Add from below
                  $ table-> string ('name');
                  $ table-> string ('password');
                  $ table-> boolean ('is_super')-> default (false);
                  $ table-> rememberToken ();
                  // Add up to the above
                  $ table-> timestamps ();
              });
          }
             
          / **
           * Reverse the migrations.
           *
           * @return void
           * /
          public function down ()
          {
              Schema :: dropIfExists ('admins');
          }
      }
             
      
    4. Execute the following command to migrate the migration file just described.

      $ php artisan migrate
      
    5. Execute the following command to open the model file created earlier.

      $ vi app / Admin.php
      
    6. Delete all the contents of the opened model file and copy and paste the following contents

      <? php
         
      namespace App;
         
      use Illuminate \ Notifications \ Notifiable;
      use Illuminate \ Foundation \ Auth \ User as Authenticatable;
         
      class Admin extends Authenticatable
      {
          use Notifiable;
         
          protected $ guard ='admin';
         
          protected $ fillable = [
              'name','password',
          ];;
         
          protected $ hidden = [
              'password','remember_token',
          ];;
      }
      
  5. Add guards and providers

    1. Execute the following command to open the file that defines the guard and provider.

      $ vi config / auth.php
      
    2. Add the description of the guard as follows.

      / *
      | ------------------------------------------------- -------------------------
      | Authentication Guards
      | ------------------------------------------------- -------------------------
      |
      | Next, you may define every authentication guard for your application.
      | Of course, a great default configuration has been defined for you
      | here which uses session storage and the Eloquent user provider.
      |
      | All authentication drivers have a user provider. This defines how the
      | users are actually retrieved out of your database or other storage
      | mechanisms used by this application to persist your user's data.
      |
      | Supported: "session", "token"
      |
      * /
         
      'guards' => [
          'web' => [
              'driver' =>' session',
              'provider' =>'users',
          ],,
         
          'api' => [
              'driver' =>'token',
              'provider' =>'users',
          ],,
          // Add the following
          'admin' => [
              'driver' =>' session',
              'provider' =>'admins',
          ],,
          // Add up to the above
      ],,
      
    3. Add the description of the provider in the same file.

      / *
      | ------------------------------------------------- -------------------------
      | User Providers
      | ------------------------------------------------- -------------------------
      |
      | All authentication drivers have a user provider. This defines how the
      | users are actually retrieved out of your database or other storage
      | mechanisms used by this application to persist your user's data.
      || If you have multiple user tables or models you may configure multiple
      | sources which represent each model / table. These sources may then
      be assigned to any extra authentication guards you have defined.
      |
      | Supported: "database", "eloquent"
      |
      * /
         
      'providers' => [
          'users' => [
              'driver' =>'eloquent',
              'model' => App \ User :: class,
          ],,
          // Add the following
          'admins' => [
              'driver' =>'eloquent',
              'model' => App \ Admin :: class,
          ],,
          // Add up to the above
         
          //'users' => [
          //'driver' =>'database',
          //'table' =>'users',
          //],
      ],,
      
    4. The entire multi_auth_info_limited / config / auth.php file after the addition is described below.

      <? php
             
      return [
             
          / *
          | ------------------------------------------------- -------------------------
          | Authentication Defaults
          | ------------------------------------------------- -------------------------
          |
          | This option controls the default authentication "guard" and password
          | reset options for your application. You may change these defaults
          | as required, but they're a perfect start for most applications.
          |
          * /
             
          'defaults' => [
              'guard' =>'web',
              'passwords' =>'users',
          ],,
             
          / *
          | ------------------------------------------------- -------------------------
          | Authentication Guards
          | ------------------------------------------------- -------------------------
          |
          | Next, you may define every authentication guard for your application.
          | Of course, a great default configuration has been defined for you
          | here which uses session storage and the Eloquent user provider.
          |
          | All authentication drivers have a user provider. This defines how the
          | users are actually retrieved out of your database or other storage
          | mechanisms used by this application to persist your user's data.
          |
          | Supported: "session", "token"
          |
          * /
             
          'guards' => [
              'web' => [
                  'driver' =>' session',
                  'provider' =>'users',
              ],,
             
              'api' => [
                  'driver' =>'token',
                  'provider' =>'users',
              ],,
              // Add the following
              'admin' => [
                  'driver' =>' session',
                  'provider' =>'admins',
              ],,
              // Add up to the above
          ],,
             
          / *
          | ------------------------------------------------- -------------------------
          | User Providers
          | ------------------------------------------------- -------------------------
          |
          | All authentication drivers have a user provider. This defines how the
          | users are actually retrieved out of your database or other storage
          | mechanisms used by this application to persist your user's data.
          |
          | If you have multiple user tables or models you may configure multiple
          | sources which represent each model / table. These sources may then
          be assigned to any extra authentication guards you have defined.
          |
          | Supported: "database", "eloquent"
          |
          * /
             
          'providers' => [
              'users' => [
                  'driver' =>'eloquent',
                  'model' => App \ User :: class,
              ],,
              // Add the following
              'admins' => [
                  'driver' =>'eloquent',
                  'model' => App \ Admin :: class,
              ],,
              // Add up to the above
              //'users' => [
              //'driver' =>'database',
              //'table' =>'users',
              //],
          ],,
             
          / *
          | ------------------------------------------------- -------------------------
          | Resetting Passwords
          | ------------------------------------------------- -------------------------
          |
          | You may specify multiple password reset configurations if you have more
          | than one user table or model in the application and you want to have
          | separate password reset settings based on the specific user types.
          |
          | The expire time is the number of minutes that the reset token should be
          | considered valid. This security feature keeps tokens short-lived so| they have less time to be guessed. You may change this as needed.
          |
          * /
             
          'passwords' => [
              'users' => [
                  'provider' =>'users',
                  'table' =>'password_resets',
                  'expire' => 60,
              ],,
          ],,
             
      ];;
      
  6. Controller modification

    1. Modify the following two controllers. –multi_auth_info_limited / app / Http / Controllers / Auth / LoginController.phpmulti_auth_info_limited / app / Http / Controllers / Auth / RegisterController.php

    2. Execute the following command to open the controller file that controls login.

      $ vi app / Http / Controllers / Auth / LoginController.php
      
    3. Modify the opened controller file as follows.

      <? php
             
      namespace App \ Http \ Controllers \ Auth;
             
      use App \ Http \ Controllers \ Controller;
      use Illuminate \ Foundation \ Auth \ AuthenticatesUsers;
             
      // Add the following
      use Illuminate \ Http \ Request;
      use Auth;
      // Add the above
             
      class LoginController extends Controller
      {
          / *
          | ------------------------------------------------- -------------------------
          | Login Controller
          | ------------------------------------------------- -------------------------
          |
          | This controller handles authenticating users for the application and
          | redirecting them to your home screen. The controller uses a trait
          | to conveniently provide its functionality to your applications.
          |
          * /
             
          use AuthenticatesUsers;
             
          / **
           * Where to redirect users after login.
           *
           * @var string
           * /
          protected $ redirectTo ='/ home';
             
          / **
           * Create a new controller instance.
           *
           * @return void
           * /
          public function __construct ()
          {
              $ this-> middleware ('guest')-> except ('logout');
              // Add the following
              $ this-> middleware ('guest: admin')-> except ('logout');
          }
             
          // Add the following
          public function showAdminLoginForm ()
          {
              return view ('auth.login', ['url' =>'admin']);
          }
             
          public function adminLogin (Request $ request)
          {
              $ this-> validate ($ request, [
                  'name' =>' required',
                  'password' =>' required | min: 6'
              ]);
             
              if (Auth :: guard ('admin')-> attempt (['name' => $ request-> name,'password' => $ request-> password], $ request-> get ('remember')) ) {
             
                  return redirect ()-> inverted ('/ admin');
              }
              return back ()-> withInput ($ request-> only ('name','remember'));
          }
          // Add the above
      }
      
    4. Execute the following command to open the controller file that controls login.

      $ vi app / Http / Controllers / Auth / RegisterController.php
      
    5. Modify the opened controller file as follows.

      <? php
             
      namespace App \ Http \ Controllers \ Auth;
             
      // Add the following
      use App \ Admin;
      use Illuminate \ Http \ Request;
      // Add up to the above
      use App \ User;
      use App \ Http \ Controllers \ Controller;
      use Illuminate \ Support \ Facades \ Hash;
      use Illuminate \ Support \ Facades \ Validator;
      use Illuminate \ Foundation \ Auth \ RegistersUsers;
             
      class RegisterController extends Controller
      {
          / *
          | ------------------------------------------------- -------------------------
          | Register Controller
          | ------------------------------------------------- -------------------------
          |
          | This controller handles the registration of new users as well as their
          | validation and creation. By default this controller uses a trait to
          | provide this functionality without requiring any additional code.
          |
          * /
             
          use RegistersUsers;
             
          / **
           * Where to redirect users after registration.
           *
           * @var string
           * /
          protected $ redirectTo ='/ home';
             
          / **
           * Create a new controller instance.
           *
           * @return void
           * /
          public function __construct ()
          {
              $ this-> middleware ('guest');
              // Add the following
              $ this-> middleware ('guest: admin');
          }
             
          / **
           * Get a validator for an incoming registration request.
           *
           * @param array $ data* @return \Illuminate\Contracts\Validation\Validator
           */
          protected function validator(array $data)
          {
              return Validator::make($data, [
                  'name' => 'required|string|max:255',
                  'email' => 'required|string|email|max:255|unique:users',
                  'password' => 'required|string|min:6|confirmed',
              ]);
          }
             
          /**
           * Create a new user instance after a valid registration.
           *
           * @param  array  $data
           * @return \App\User
           */
          protected function create(array $data)
          {
              return User::create([
                  'name' => $data['name'],
                  'email' => $data['email'],
                  'password' => Hash::make($data['password']),
              ]);
          }
          //下記を追記する
          protected function validatorAdmin(array $data)
          {
              return Validator::make($data, [
                  'name' => 'required|string|max:255',
                  'password' => 'required|string|min:6|confirmed',
              ]);
          }
      
          public function showAdminRegisterForm()
          {
              return view('auth.register', ['url' => 'admin']);
          }
             
          protected function createAdmin(Request $request)
          {
              $this->validatorAdmin($request->all())->validate();
              $admin = Admin::create([
                  'name' => $request['name'],
                  'password' => Hash::make($request['password']),
              ]);
              return redirect()->intended('login/admin');
          }
          //上記までを追記する
      }
      
  7. 管理者ログインページのビューファイルの修正

    1. 下記コマンドを実行してログインページのビューファイルを開く。

      $ vi resources/views/auth/login.blade.php
      
    2. 開いたビューファイルを下記の様に修正する。(修正内容が複雑で分かりにくい時は下記をまるまるコピーして貼り付けてもOKである)

      @extends('layouts.app')
             
      @section('content')
      <div class="container">
          <div class="row justify-content-center">
              <div class="col-md-8">
                  <div class="card">
                      <!-- 下記を修正する -->
                      <div class="card-header"> {{ isset($url) ? ucwords($url) : ""}} {{ __('Login') }}</div>
             
                      <div class="card-body">
                          @isset($url)
                          <form method="POST" action='{{ url("login/$url") }}' aria-label="{{ __('Login') }}">
                              @csrf
             
                              <div class="form-group row">
                                  <label for="name" class="col-sm-4 col-form-label text-md-right">{{ __('Name') }}</label>
             
                                  <div class="col-md-6">
                                      <input id="name" type="name" class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}" name="name" value="{{ old('name') }}" required autofocus>
             
                                      @if ($errors->has('name'))
                                          <span class="invalid-feedback" role="alert">
                                              <strong>{{ $errors->first('name') }}</strong>
                                          </span>
                                      @endif
                                  </div>
                              </div>
             
                              <div class="form-group row">
                                  <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
             
                                  <div class="col-md-6">
                                      <input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
             
                                      @if ($errors->has('password'))
                                          <span class="invalid-feedback" role="alert">
                                              <strong>{{ $errors->first('password') }}</strong>
                                          </span>
                                      @endif
                                  </div>
                              </div>
                          @else
                          <form method="POST" action="{{ route('login') }}" aria-label="{{ __('Login') }}">
                              @csrf
             
                              <div class="form-group row">
                                  <label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
             
                                  <div class="col-md-6"><input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required autofocus>
             
                                      @if ($errors->has('email'))
                                          <span class="invalid-feedback" role="alert">
                                              <strong>{{ $errors->first('email') }}</strong>
                                          </span>
                                      @endif
                                  </div>
                              </div>
             
                              <div class="form-group row">
                                  <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
             
                                  <div class="col-md-6">
                                      <input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
             
                                      @if ($errors->has('password'))
                                          <span class="invalid-feedback" role="alert">
                                              <strong>{{ $errors->first('password') }}</strong>
                                          </span>
                                      @endif
                                  </div>
                              </div>
                          @endisset
                              <!-- 上記までを修正する -->
                              <div class="form-group row">
                                  <div class="col-md-6 offset-md-4">
                                      <div class="form-check">
                                          <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
             
                                          <label class="form-check-label" for="remember">
                                              {{ __('Remember Me') }}
                                          </label>
                                      </div>
                                  </div>
                              </div>
             
                              <div class="form-group row mb-0">
                                  <div class="col-md-8 offset-md-4">
                                      <button type="submit" class="btn btn-primary">
                                          {{ __('Login') }}
                                      </button>
             
                                      <a class="btn btn-link" href="{{ route('password.request') }}">
                                          {{ __('Forgot Your Password?') }}
                                      </a>
                                  </div>
                              </div>
                          </form>
                      </div>
                  </div>
              </div>
          </div>
      </div>
      @endsection
      
  8. 管理者登録ページのビューファイルの修正

    1. 下記コマンドを実行してログインページのビューファイルを開く。

      $ vi resources/views/auth/register.blade.php
      
    2. 開いたビューファイルを下記の様に修正する。(修正内容が複雑で分かりにくい時は下記をまるまるコピーして貼り付けてもOKである)

      @extends('layouts.app')
             
      @section('content')
      <div class="container">
          <div class="row justify-content-center">
              <div class="col-md-8">
                  <div class="card">
                      <!-- 下記を修正する -->
                      <div class="card-header"> {{ isset($url) ? ucwords($url) : ""}} {{ __('Register') }}</div>
             
                      <div class="card-body">
                          @isset($url)
                          <form method="POST" action='{{ url("register/$url") }}' aria-label="{{ __('Register') }}">
                              @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{{ $errors->has('name') ? ' is-invalid' : '' }}" name="name" value="{{ old('name') }}" required autofocus>
             
                                      @if ($errors->has('name'))
                                          <span class="invalid-feedback" role="alert">
                                              <strong>{{ $errors->first('name') }}</strong>
                                          </span>
                                      @endif
                                  </div></div>
      
                              <div class="form-group row">
                                  <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
             
                                  <div class="col-md-6">
                                      <input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
             
                                      @if ($errors->has('password'))
                                          <span class="invalid-feedback" role="alert">
                                              <strong>{{ $errors->first('password') }}</strong>
                                          </span>
                                      @endif
                                  </div>
                              </div>
             
                              <div class="form-group row">
                                  <label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
             
                                  <div class="col-md-6">
                                      <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
                                  </div>
                              </div>
                          @else
                          <form method="POST" action="{{ route('register') }}" aria-label="{{ __('Register') }}">
                              @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{{ $errors->has('name') ? ' is-invalid' : '' }}" name="name" value="{{ old('name') }}" required autofocus>
             
                                      @if ($errors->has('name'))
                                          <span class="invalid-feedback" role="alert">
                                              <strong>{{ $errors->first('name') }}</strong>
                                          </span>
                                      @endif
                                  </div>
                              </div>
             
                              <div class="form-group row">
                                  <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
             
                                  <div class="col-md-6">
                                      <input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required>
             
                                      @if ($errors->has('email'))
                                          <span class="invalid-feedback" role="alert">
                                              <strong>{{ $errors->first('email') }}</strong>
                                          </span>
                                      @endif
                                  </div>
                              </div>
             
                              <div class="form-group row">
                                  <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
             
                                  <div class="col-md-6">
                                      <input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
             
                                      @if ($errors->has('password'))
                                          <span class="invalid-feedback" role="alert">
                                              <strong>{{ $errors->first('password') }}</strong>
                                          </span>
                                      @endif
                                  </div>
                              </div>
             
                              <div class="form-group row">
                                  <label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
             
                                  <div class="col-md-6">
                                      <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
                                  </div>
                              </div>
      
                          @endisset
                          <!-- 上記までを修正する --><div class = "form-group row mb-0">
                                  <div class = "col-md-6 offset-md-4">
                                      <button type = "submit" class = "btn btn-primary">
                                          {{__ ('Register')}}
                                      </ button>
                                  </ div>
                              </ div>
                          </ form>
                      </ div>
                  </ div>
              </ div>
          </ div>
      </ div>
      @endsection
      
  9. Creating a transition page after authentication

    1. Execute the following command to create a view file.

      $ touch resources / views / layouts / auth.blade.php
      $ touch resources / views / admin.blade.php
      
    2. Execute the following command to open the view file created earlier.

      $ vi resources / views / layouts / auth.blade.php
      
    3. Copy and paste the following contents.

      <!DOCTYPE html>
      <html lang = "{{str_replace ('_','-', app ()-> getLocale ())}}">
      <head>
          <meta charset = "utf-8">
          <meta http-equiv = "X-UA-Compatible" content = "IE = edge">
          <meta name = "viewport" content = "width = device-width, initial-scale = 1">
         
          <!-CSRF Token->
          <meta name = "csrf-token" content = "{{csrf_token ()}}">
         
          <title> {{config ('app.name','Laravel')}} </ title>
         
          <!-Scripts->
          <script src = "{{asset ('js / app.js')}}" defer> </ script>
         
          <!-Fonts->
          <link rel = "dns-prefetch" href = "https://fonts.gstatic.com">
          <link href = "https://fonts.googleapis.com/css?family=Raleway:300,400,600" rel = "stylesheet" type = "text / css">
         
          <!-Styles->
          <link href = "{{asset ('css / app.css')}}" rel = "stylesheet">
      </ head>
      <body>
          <div id = "app">
              <nav class = "navbar navbar-expand-md navbar-light navbar-laravel">
                  <div class = "container">
                      <a class="navbar-brand" href="{{url('/')}}">
                          {{config ('app.name','Laravel')}}
                      </a>
                      <button class = "navbar-toggler" type = "button" data-toggle = "collapse" data-target = "# navbarSupportedContent" aria-controls = "navbarSupportedContent" aria-expanded = "false" aria-label = "{{ __ ('Toggle navigation')}} ">
                          <span class = "navbar-toggler-icon"> </ span>
                      </ button>
         
                      <div class = "collapse navbar-collapse" id = "navbarSupportedContent">
                          <!-Left Side Of Navbar->
                          <ul class = "navbar-nav mr-auto">
         
                          </ ul>
         
                          <!-Right Side Of Navbar->
                          <ul class = "navbar-nav ml-auto">
                              <!-Authentication Links->
                             <li class = "nav-item dropdown">
                                  <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v- pre>
                                      Hi There <span class = "caret"> </ span>
                                  </a>
         
                                  <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>
         
                                      <form id = "logout-form" action = "{{route ('logout')}}" method = "POST" style = "display: none;">
                                          @csrf
                                      </ form>
                                  </ div>
                              </ li>
                          </ ul>
                      </ div>
                  </ div>
              </ nav>
         
              <main class = "py-4">
                  @yield ('content')
              </ main>
          </ div>
      </ body>
      </ html>
      
    4. Execute the following command to open the view file created earlier.

      $ vi resources / views / admin.blade.php
      
    5. Copy and paste the following contents.

      @extends ('layouts.auth')
         
      @section ('content')
      <div class = "container">
          <div class = "row justify-content-center">
              <div class = "col-md-8">
                  <div class = "card"><div class = "card-header"> Dashboard </ div>
         
                      <div class = "card-body">
                          Hi boss!
                      </ div>
                  </ div>
              </ div>
          </ div>
      </ div>
      @endsection
      
    6. Execute the following command to open the view file created earlier.

      $ vi resources / views / home.blade.php
      
    7. Delete the contents already described and paste the following contents by copy and paste.

      @extends ('layouts.auth')
         
      @section ('content')
      <div class = "container">
          <div class = "row justify-content-center">
              <div class = "col-md-8">
                  <div class = "card">
                      <div class = "card-header"> Dashboard </ div>
         
                      <div class = "card-body">
                           Hi there, regular user
                      </ div>
                  </ div>
              </ div>
          </ div>
      </ div>
      @endsection
      
  10. Description of routing, setting of transition page after authentication, and description of processing at exception

    1. Execute the following command to open the routing file.

      $ vi routes / web.php
      
    2. Add as follows.

      <? php
             
      / *
      | ------------------------------------------------- -------------------------
      | Web Routes
      | ------------------------------------------------- -------------------------
      |
      Here is where you can register web routes for your application. These
      | routes are loaded by the RouteServiceProvider within a group which
      | contains the "web" middleware group. Now create something great!
      |
      * /
             
      Route :: get ('/', function () {
          return view ('welcome');
      });
             
      Auth :: routes ();
             
      Route :: get ('/ home','HomeController @ index')-> name ('home');
             
      // Add the following
      Route :: get ('/ login / admin','Auth \ LoginController @ showAdminLoginForm');
      Route :: get ('/ register / admin','Auth \ RegisterController @ showAdminRegisterForm');
             
      Route :: post ('/ login / admin','Auth \ LoginController @ adminLogin');
      Route :: post ('/ register / admin','Auth \ RegisterController @ createAdmin');
             
      Route :: view ('/ home','home')-> middleware ('auth');
      Route :: view ('/ admin','admin');
      // Add up to the above
      
  11. Redirect settings

    1. Execute the following command to open the middleware file that controls the redirect.

      $ vi app / Http / Middleware / RedirectIfAuthenticated.php
      
    2. Add as follows.

      <? php
         
      namespace App \ Http \ Middleware;
         
      use Closure;
      use Illuminate \ Support \ Facades \ Auth;
         
      class RedirectIfAuthenticated
      {
          public function handle ($ request, Closure $ next, $ guard = null)
          {
              // Add the following
              if ($ guard == "admin" && Auth :: guard ($ guard)-> check ()) {
                  return redirect ('/ admin');
              }
              // Add the above
              if (Auth :: guard ($ guard)-> check ()) {
                  return redirect ('/ home');
              }
         
              return $ next ($ request);
          }
      }
      
  12. Exception settings

    1. Execute the following command to open the handler file.

      $ vi app /Exceptions/Handler.php
      
    2. Modify the handler file as shown below.

      <? php
             
      namespace App \ Exceptions;
             
      use Exception;
      use Illuminate \ Foundation \ Exceptions \ Handler as ExceptionHandler;
             
      // Add the following
      use Illuminate \ Auth \ AuthenticationException;
      use Auth;
      // Add up to the above
             
      class Handler extends ExceptionHandler
      {
          / **
           * A list of the exception types that are not reported.
           *
           * @var array
           * /
          protected $ dontReport = [
              // //
          ];;
             
          / **
           * A list of the inputs that are never flashed for validation exceptions.
           *
           * @var array
           * /
          protected $ dontFlash = [
              'password',
              'password_confirmation',
          ];;
             
          / **
           * Report or log an exception.
           *
           * @param \ Exception $ exception
           * @return void
           * /
          public function report (Exception $ exception)
          {
              parent :: report ($ exception);
          }
             
          / **
           * Render an exception into an HTTP response.
           *
           * @param \ Illuminate \ Http \ Request $ request
           * @param \ Exception $ exception
           * @return \ Illuminate \ Http \ Response
           * /public function render ($ request, Exception $ exception)
          {
              return parent :: render ($ request, $ exception);
          }
          // Add the following
          protected function unauthenticated ($ request, AuthenticationException $ exception)
          {
              if ($ request-> expectsJson ()) {
                  return response ()-> json (['error' =>'Unauthenticated.'], 401);
              }
              if ($ request-> is ('admin') || $ request-> is ('admin / *')) {
                  return redirect ()-> guest ('/ login / admin');
              }
              return redirect ()-> guest (route ('login'));
          }
          // Add up to the above
             
      }
      
  13. Confirmation

    1. Execute the following command to start the local server.

      $ php artisan serve
      
    2. Access the following and confirm that the initial screen of Laravel is displayed. -http://localhost:8000/

       ![Laravel.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/306417/2c3f4343-8ee0-c775-fa5e-79964bfead6d.png)
      
    3. Access the following, enter the required information, and click “Registar”. -[http://localhost:8000/ register / admin](http://localhost:8000/ register / admin)

       ![Laravel-9.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/306417/3fea063e-776d-932f-0a84-eda6871692b1.png)
      
    4. Confirm that you are redirected to the screen below. Enter the information at the time of administrator registration entered in the previous step and click “Login”.

      Laravel-10.png

    5. If the following page “Hi boss!” Is displayed, login as an administrator is complete.

      Laravel.png

#References