Laravel 7/6をインストールする

通常の認証を組み込んだインストールを行います。

 laravel new [appName]  --auth

データベース構成

.envファイルのDB_セクションに登録します。

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=[dbname]
DB_USERNAME=root
DB_PASSWORD=

移行とモデルを更新

database/migrations/00_create_users_table.phpを変更します

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->boolean('is_admin')->nullable();   //* 追加 *//
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

app/User.phpファイルも変更します

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'is_admin'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

この段階で

php artisan migrate

を実行します。

IsAdmin ミドルウェアの作成

php artisan make:middleware IsAdmin

作成されたapp/Http/middleware/IsAdmin.phpを以下のように設定ます。

<?php

namespace App\Http\Middleware;

use Closure;

class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(auth()->user()->is_admin == 1){
            return $next($request);
        }
        return redirect(‘home’)->with(‘error’,"You don't have admin access.");
    }
}

作成したミドルウエアをapp/Http/Kernel.phpに登録します。

....
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'is_admin' => \App\Http\Middleware\IsAdmin::class,  //* この行を追加 *//
];
....

IsAdmin ルートの作成

routes/web.phpファイルに以下を追加します。

Route::get('admin/home', 'HomeController@adminHome')->name('admin.home')->middleware('is_admin');

この段階でのルートリスト

php artisan route:list
+--------+----------+------------------------+------------------+------------------------------------------------------------------------+-------------------+
| Domain | Method   | URI                    | Name             | Action                                                                 | Middleware        |
+--------+----------+------------------------+------------------+------------------------------------------------------------------------+-------------------+
|        | GET|HEAD | /                      |                  | Closure                                                                | web               |
|        | GET|HEAD | admin/home             | admin.home       | App\Http\Controllers\HomeController@adminHome                          | web,is_admin,auth |
|        | GET|HEAD | api/user               |                  | Closure                                                                | api,auth:api      |
|        | GET|HEAD | home                   | home             | App\Http\Controllers\HomeController@index                              | web,auth          |
|        | GET|HEAD | login                  | login            | App\Http\Controllers\Auth\LoginController@showLoginForm                | web,guest         |
|        | POST     | login                  |                  | App\Http\Controllers\Auth\LoginController@login                        | web,guest         |
|        | POST     | logout                 | logout           | App\Http\Controllers\Auth\LoginController@logout                       | web               |
|        | GET|HEAD | password/confirm       | password.confirm | App\Http\Controllers\Auth\ConfirmPasswordController@showConfirmForm    | web,auth          |
|        | POST     | password/confirm       |                  | App\Http\Controllers\Auth\ConfirmPasswordController@confirm            | web,auth          |
|        | POST     | password/email         | password.email   | App\Http\Controllers\Auth\ForgotPasswordController@sendResetLinkEmail  | web               |
|        | GET|HEAD | password/reset         | password.request | App\Http\Controllers\Auth\ForgotPasswordController@showLinkRequestForm | web               |
|        | POST     | password/reset         | password.update  | App\Http\Controllers\Auth\ResetPasswordController@reset                | web               |
|        | GET|HEAD | password/reset/{token} | password.reset   | App\Http\Controllers\Auth\ResetPasswordController@showResetForm        | web               |
|        | GET|HEAD | register               | register         | App\Http\Controllers\Auth\RegisterController@showRegistrationForm      | web,guest         |
|        | POST     | register               |                  | App\Http\Controllers\Auth\RegisterController@register                  | web,guest         |
+--------+----------+------------------------+------------------+------------------------------------------------------------------------+-------------------+

コントローラにメソッドを追加します。

app/Http/Controllers/HomeController.phpを以下のようにします。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function adminHome()
    {
        return view('adminHome');
    }

}

一般ユーザーはreturn view(‘home’); 管理者は、adminHomeに振り分けられます。

Blade fileの作成

resources/views/home.blade.php(一般ユーザー)用

@extends('layouts.app')
@section('content')
Dashboard
You are normal user.
@endsection

resources/views/adminHome.blade.php(管理者ユーザー)用ファイル

@extends('layouts.app') 
@section('content')
Dashboard 
You are admin user.
@endsection

LoginControllerの更新

LoginControllerを変更し、ユーザーアクセスに従ってリダイレクトします。

通常のユーザーの場合はホームルートにリダイレクトし、管理ユーザーの場合は管理ルートにリダイレクトします。

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

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');
    }

    public function login(Request $request)
    {
        $input = $request->all();

        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if(auth()->attempt(array('email' => $input['email'], 'password' => $input['password'])))
        {
            if (auth()->user()->is_admin == 1) {
                return redirect()->route('admin.home');
            }else{
                return redirect()->route('home');
            }
        }else{
            return redirect()->route('login')
                ->with('error','Email-Address And Password Are Wrong.');
        }

    }
}

テスト用にシーダーファイルを作成します

php artisan make:seeder CreateUsersSeeder

コマンドでdatabase/seeds/CreateUsersSeeder.phpを作成し、以下のようにします

<?php

use Illuminate\Database\Seeder;
use App\User;

class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $user = [
            [
               'name'=>'Admin',
               'email'=>'admin@itsolutionstuff.com',
                'is_admin'=>'1',
               'password'=> bcrypt('123456'),
            ],
            [
               'name'=>'User',
               'email'=>'user@itsolutionstuff.com',
                'is_admin'=>'0',
               'password'=> bcrypt('123456'),
            ],
        ];

        foreach ($user as $key => $value) {
            User::create($value);
        }
    }
}

シーダーの実行

php artisan db:seed --class=CreateUsersSeeder

テスト用データが作成されます。

サーバーの実行

php artisan serve

Loginメニューで作成した一般ユーザー(user@itsolutionstuff.com)と管理者ユーザー(admin@itsolutionstuff.com)でそれぞれログインしてみます。