Separate Laravel6 user and administrator authentication

Aug 24, 2020 PHP Beginner Laravel For Beginners Laravel6

Purpose

Implementation environment

Item 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
Item Information Remarks
PHP version 7.4.3 Introduced using Homwbrew
Laravel version 6.18.35 Introduced by this method using commposer → Construct environment of Mac Laravel
MySQL version 8.0.19 for osx10.13 on x86_64 Introduced by this method using Homwbrew → Install MySQL with Mac Homebrew

#Prerequisites

#Prerequisite information

After reading

Overview

  1. Creating a database
  2. Laravel application creation and initial settings
  3. Creation of user authentication function
  4. Preparation of administrator information table
  5. Adding guards and providers
  6. Modify the controller
  7. Creating an authentication page
  8. Creating post-authentication transition page
  9. Description of routing and setting of transition page after authentication and description of processing at the time of exception
  10. Confirm

#Details

  1. Creating a database

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

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

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

      show databases;
      
  2. Laravel application creation and initial settings

    1. Change to the directory where you want to create the Laravel application.

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

      $ composer create-project laravel/laravel multi_auth_info_limited_laravel_6 "5.6.*"
      
    3. Move to the application name directory created by executing the following command. Unless otherwise specified, the following commands are executed inside this multi_auth directory.

      $ cd multi_auth_info_limited_laravel_6
      
    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_laravel_6
      DB_USERNAME=root
      DB_PASSWORD=mysql -u root -p password entered when executing the 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 differs 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_laravel_6
      DB_USERNAME=root
      DB_PASSWORD=Mysql root user password 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. Creation of user authentication function

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

      $ composer require laravel/ui "^1.0" --dev
      $ php artisan ui vue --auth
      $ npm install && npm run dev
      
    2. Execute the following command to start the local server.

      $ php artisan serve
      
    3. Open the Laravel initial screen by accessing the following. -http://localhost:8000/Laravel.png

    4. Click “REGISTER” on the upper right.

      Laravel.png

    5. Enter various information and click “Register”.

      Laravel-2.png

    6. Confirm that the screen moves to the corner after clicking “Register”.

      Laravel-3.pngLaravel.png

  4. Preparation of administrator information table

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

      $ php artisan make:model Admin -m
      
    2. Execute the following command to open the migration file created earlier. (The YYYY_MM_DD_XXXXXX part depends 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 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 contents below.

      <?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. Adding 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,
          ],
          //下記を追記する
          'admins' => [
              'driver' => 'eloquent',
              'model' => App\Admin::class,
          ],
          //上記までを追記する
         
          // 'users' => [
          //     'driver' => 'database',
          //     'table' => 'users',
          // ],
      ],
      
    4. 追記後のmulti_auth_info_limited_laravel_6/config/auth.phpのファイルの全体を下記に記載する。

      <?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',
              ],
              //下記を追記する
              'admin' => [
                  'driver' => 'session',
                  'provider' => 'admins',
              ],
              //上記までを追記する
          ],
             
          /*
          |--------------------------------------------------------------------------
          | 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,
              ],
              //下記を追記する
              'admins' => [
                  'driver' => 'eloquent',
                  'model' => App\Admin::class,
              ],
              //上記までを追記する
              // '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. Modify the controller

    1. Modify the following two controllers. -multi_auth_info_limited_laravel_6/app/Http/Controllers/Auth/LoginController.php -multi_auth_info_limited_laravel_6/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 up to 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()->intended('/admin');
              }
              return back()->withInput($request->only('name','remember'));
          }
          // Add up to 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 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');
              //下記を追記する
              $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
                          <!-- Modify the above -->
                              <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 post-authentication transition page

    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. Paste the following contents by copy and paste.

      <!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. Paste the following contents by copy and paste.```multi_auth_info_limited_laravel_6/resources/views/admin.blade.php @extends(‘layouts.auth’)

      @section(‘content’)

      Dashboard
                   <div class="card-body">
                       Hi boss!
                   </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 and setting of transition page after authentication and description of processing at the time of 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.
      | 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 the above
      
  11. Redirect settings

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

      $ 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 up to 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 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);
          }
          //下記を追記する
          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'));
          }
          //上記までを追記する
             
      }
      
  13. 確認

    1. 下記コマンドを実行してローカルサーバを起動する。

      $ php artisan serve
      
    2. 下記にアクセスしてLaravelの初期画面が表示されることを確認する。

    3. 下記にアクセスし必要情報を入力後「Registar」をクリックする。

    4. 下記の画面にリダイレクトすることを確認する。一つ前の手順で入力した管理者登録時の情報を入力し「Login」をクリックする。

      Laravel-10.png

    5. 下記のページ「Hi boss!」が表示されれば管理者としてのログインは完了である。

      Laravel.png

参考文献