0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravelのマルチ認証システム

Last updated at Posted at 2024-12-20

はじめに

この記事は、Laravel Advent Calendar 2024の一環として、Rails学習者向けにLaravelのマルチ認証システムについて解説します。RailsでDeviseを使った認証を経験している方にとって、Laravelでの認証システムの構築方法を理解する助けになれば幸いです。

マルチ認証とは?

マルチ認証とは、アプリケーションで異なる種類のユーザー(例: 管理者、一般ユーザー)に対して別々の認証ロジックを適用する仕組みです。RailsではDeviseのスコープを使って実現しますが、LaravelではGuardとMiddlewareを活用して構築します。

前提条件

Laravelの基本的な環境構築が完了していること

Laravelの基礎的な知識があること(Routing, Controller, Modelの操作など)

ComposerとPHPがインストールされていること

Laravelのバージョンは8以上を想定

ステップ1: 認証システムのインストール

Laravelはデフォルトでlaravel/uiパッケージを用いた認証システムをサポートしています。以下のコマンドでパッケージをインストールします。

composer require laravel/ui --dev
php artisan ui bootstrap --auth
npm install && npm run dev
php artisan migrate

これにより、ログイン・登録機能が使用可能になります。

ステップ2: マルチ認証用のGuard設定

Guardの設定

LaravelではGuardを用いて複数の認証ロジックを管理します。config/auth.phpファイルを編集して、Guardを設定します。

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],

    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
],

Adminモデルの作成

管理者専用のモデルを作成します。

php artisan make:model Admin -m

database/migrationsフォルダに生成されたマイグレーションファイルを編集し、adminsテーブルのスキーマを定義します。

Schema::create('admins', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->timestamps();
});

その後、マイグレーションを実行します。

php artisan migrate

ステップ3: Middlewareの設定

管理者専用の認証Middlewareを作成します。

php artisan make:middleware AdminMiddleware

app/Http/Middleware/AdminMiddleware.phpを以下のように編集します。

public function handle($request, Closure $next)
{
    if (!auth('admin')->check()) {
        return redirect('/admin/login');
    }

    return $next($request);
}

このMiddlewareをapp/Http/Kernel.phpに登録します。

protected $routeMiddleware = [
    'admin' => \App\Http\Middleware\AdminMiddleware::class,
];

ステップ4: 管理者用ルートの設定

管理者専用のルートを設定します。routes/web.phpを編集します。

Route::prefix('admin')->group(function () {
    Route::get('login', [AdminController::class, 'showLoginForm'])->name('admin.login');
    Route::post('login', [AdminController::class, 'login']);
    Route::middleware('admin')->group(function () {
        Route::get('dashboard', [AdminController::class, 'dashboard'])->name('admin.dashboard');
    });
});

ステップ5: 管理者認証の実装

管理者ログイン用のコントローラを作成します。

php artisan make:controller AdminController

以下のようにAdminControllerを編集します。

use Illuminate\Support\Facades\Auth;

class AdminController extends Controller
{
    public function showLoginForm()
    {
        return view('admin.login');
    }

    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::guard('admin')->attempt($credentials)) {
            return redirect()->route('admin.dashboard');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ]);
    }

    public function dashboard()
    {
        return view('admin.dashboard');
    }
}

まとめ

この記事では、Laravelでマルチ認証システムを構築する方法を解説しました。Rails学習者にも馴染みのある概念を用いながら、GuardやMiddlewareを活用するLaravel独自の方法論に触れました。

Laravel公式ドキュメントも併せて参照し、理解を深めてください。

Laravel Documentation - Authentication

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?