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
- -Summary of how to separate authentication between user and administrator.
Implementation environment
- -Hardware 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 |
- -Software environment
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.
- -Laravel is built for the latest version, but it is created by specifying 5.6 when executing the application creation command.
Prerequisite information
- -Create a Laravel app directly in your Mac’s local environment without using Docker or AWS. ――Since it is a slightly difficult task, describe it carefully so that it is as easy to understand as possible. ――If you implement the contents of this article from the beginning, we aim to enable anyone to authenticate separately for users and administrators.
- -Administrator authentication information is the administrator name and password.
- -To avoid complication of work, the password for the administrator will not be changed from the application side.
- -Additionally edit the existing Auth authentication controller to create an administrator authentication function.
- -Implement only the required name part by referring to the following document. Also, the order of implementation will be changed slightly to make the explanation easier to understand. -How to use multiple authentication guards in your Laravel app ――We will apply the contents of the following article, but for the sake of clarity, we will describe it in this article from the application creation part.
Feeling after reading
- -Since Laravel 5.6, you can create an application with user authentication and administrator authentication functions, and the administrator authentication information is the administrator name and password.
Overview
- Creating a database
- Create and initialize Laravel app
- Create user authentication function
- Preparation of table for administrator information
- Add guards and providers
- Controller modification
- Creating an authentication page
- Creating a transition page after authentication
- Description of routing, setting of transition page after authentication, and description of processing at exception
- Confirmation
#Details
-
Creating a database
-
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
-
Execute the following SQL to create a “multi_auth” database.
create database multi_auth_info_limited;
-
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;
-
-
Create and initialize Laravel app
-
Move to any directory where you want to create the Laravel app.
-
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. *"
-
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
-
Execute the following command to open the .env file.
$ vi .env
-
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
-
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}"
-
Execute the following command to migrate the initial migration file.
$ php artisan migrate
-
Execute the following command to start the local server.
$ php artisan serve
-
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)
-
-
Create user authentication function
-
Execute the following command to create a user authentication function.
$ php artisan make: auth
-
Execute the following command to start the local server.
$ php artisan serve
-
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)
-
Click “REGISTER” on the upper right.
-
Enter various information and click “Register”.
-
Click “Register” and confirm that the screen changes to the dorsal horn screen.
![Laravel-3.png]!.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/306417/6aefa2ea-9b95-ff79-484f-aedf92de18a0.png)
-
-
Preparation of table for administrator information
-
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
-
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
-
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'); } }
-
Execute the following command to migrate the migration file just described.
$ php artisan migrate
-
Execute the following command to open the model file created earlier.
$ vi app / Admin.php
-
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', ];; }
-
-
Add guards and providers
-
Execute the following command to open the file that defines the guard and provider.
$ vi config / auth.php
-
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 ],,
-
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', //], ],,
-
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, ],, ],, ];;
-
-
Controller modification
-
Modify the following two controllers. –
multi_auth_info_limited / app / Http / Controllers / Auth / LoginController.php
–multi_auth_info_limited / app / Http / Controllers / Auth / RegisterController.php
-
Execute the following command to open the controller file that controls login.
$ vi app / Http / Controllers / Auth / LoginController.php
-
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 }
-
Execute the following command to open the controller file that controls login.
$ vi app / Http / Controllers / Auth / RegisterController.php
-
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'); } //上記までを追記する }
-
-
管理者ログインページのビューファイルの修正
-
下記コマンドを実行してログインページのビューファイルを開く。
$ vi resources/views/auth/login.blade.php
-
開いたビューファイルを下記の様に修正する。(修正内容が複雑で分かりにくい時は下記をまるまるコピーして貼り付けても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
-
-
管理者登録ページのビューファイルの修正
-
下記コマンドを実行してログインページのビューファイルを開く。
$ vi resources/views/auth/register.blade.php
-
開いたビューファイルを下記の様に修正する。(修正内容が複雑で分かりにくい時は下記をまるまるコピーして貼り付けても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
-
-
Creating a transition page after authentication
-
Execute the following command to create a view file.
$ touch resources / views / layouts / auth.blade.php $ touch resources / views / admin.blade.php
-
Execute the following command to open the view file created earlier.
$ vi resources / views / layouts / auth.blade.php
-
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>
-
Execute the following command to open the view file created earlier.
$ vi resources / views / admin.blade.php
-
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
-
Execute the following command to open the view file created earlier.
$ vi resources / views / home.blade.php
-
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
-
-
Description of routing, setting of transition page after authentication, and description of processing at exception
-
Execute the following command to open the routing file.
$ vi routes / web.php
-
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
-
-
Redirect settings
-
Execute the following command to open the middleware file that controls the redirect.
$ vi app / Http / Middleware / RedirectIfAuthenticated.php
-
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); } }
-
-
Exception settings
-
Execute the following command to open the handler file.
$ vi app /Exceptions/Handler.php
-
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 }
-
-
Confirmation
-
Execute the following command to start the local server.
$ php artisan serve
-
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)
-
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)
-
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”.
-
If the following page “Hi boss!” Is displayed, login as an administrator is complete.
-
#References