Laravel6 管理者ログインを実装する

Laravel5Laravel
この記事は 約10 分で読めます。

Laravelでサイトを制作しているとログインを複数の種類に分けたい時がある。

例えば 管理者として自由に管理パネルを閲覧出来る権限と一般ユーザーのログインを分けたい場合などなど
今回は管理者専用ページを自由に閲覧・編集出来るログインと一般ユーザーのログイン窓口から分けるやり方を覚えたのでメモ

スポンサーリンク

管理者コントローラー AdminController

namespace App\Http\Controllers;
use Illuminate\Http\Request;
 
class AdminController extends Controller { 
    public function index(Request $request){ 
        echo "You are admin!";
        dd($request->user());
    }
}

Loginコントローラー

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class LoginController extends Controller
{
    public function adminLogin(Request $request){
        return view('admin.login');
    }
}

Karnel.php に追記

ファイルの最初にuseを追加

use App\Http\Middleware\AdminAuthMiddleware;
namespace App\Http;

use App\Http\Middleware\AdminAuthMiddleware;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    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,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'auth.admin'=> AdminAuthMiddleware::class
    ];

    /**
     * The priority-sorted list of middleware.
     *
     * This forces non-global middleware to always be in the given order.
     *
     * @var array
     */
    protected $middlewarePriority = [
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Routing\Middleware\ThrottleRequests::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ];
}

$routeMiddlewareの最後にClassを追記

'auth.admin'=> AdminAuthMiddleware::class

Middlewareを制作

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Support\Facades\Auth;

class AdminAuthMiddleware extends Middleware
{

    public function handle($request, Closure $next, ...$guards)
    {
        if (Auth::user() &&  Auth::user()->user_type === 'administrator') {
            return $next($request);
        }

        return redirect()->route('admin.login')->with('status','ログインしてください');
    }

    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('admin.login');
        }
    }
}

以上で完成だがWeb.phpでのルートの書き方を以下に紹介する

Web.phpの書き方

Route::get('/admin', 'AdminController@index')->name('admin.index');
Route::get('/adminLogin', 'LoginController@adminLogin')->name('admin.login');

Route::group(['middleware' => 'auth.admin'], function()
{
    Route::get('/admin', 'AdminController@index')->name('admin.index');
  // ここに書いたルートは全てAdminセッションを持っていないとログインページにリダイレクトされる。
});

すごく簡単に書いたが実は結構難しかったw

トップへ戻る