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 12 + Fortify その1 カスタム認証を実装する方法

Posted at

はじめに

Laravel 12は2024年2月リリースのLTS版です。
この記事では、Laravel 12環境でFortifyを使い、カスタム認証(例えばユーザーコードでのログイン)を実装する方法を解説します。


前提条件

  • Laravel 12 プロジェクト(インストール済み)
  • Fortify 導入済み
  • 基本的なLaravelの知識

1. Fortifyのインストール

composer require laravel/fortify
php artisan vendor:publish --provider="Laravel\\Fortify\\FortifyServiceProvider"
php artisan migrate

2. FortifyのServiceProviderを有効化

config/app.phpproviders
Laravel\Fortify\FortifyServiceProvider::class が含まれていることを確認。


3. Fortifyのカスタム認証ロジックを追加

app/Providers/FortifyServiceProvider.php を編集します。

use Illuminate\Http\Request;
use Laravel\Fortify\Fortify;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

public function boot()
{
    Fortify::authenticateUsing(function (Request $request) {
        // 例: ユーザーコード認証
        $user = User::where('user_code', $request->user_code)->first();

        if ($user && Hash::check($request->password, $user->password)) {
            return $user;
        }
        return null;
    });
}

4. バリデーションの追加

app/Actions/Fortify/AttemptToAuthenticate.php など、必要に応じてリクエストバリデーションを調整します。

public function rules(Request $request)
{
    return [
        'user_code' => ['required', 'string'],
        'password' => ['required', 'string'],
    ];
}

5. ログインリクエストの例

POST /login に対し、以下のようなJSONでリクエストします。

{
    "user_code": "sample123",
    "password": "secret"
}

6. まとめ

Laravel 12でもFortifyを使うことで、簡単にカスタム認証を実装できます。
Fortify::authenticateUsing を活用し、独自の認証要件にも柔軟に対応しましょう。


参考リンク

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?