はじめに
前回の記事「その1」では、Laravel 12 + Fortifyでカスタム認証(ユーザーコード認証など)のバックエンド実装について解説しました。
今回は、FortifyのAPI認証とBladeテンプレート(UI)を連携し、カスタム認証フォームを作成する方法をまとめます。
前提
- Laravel 12 プロジェクト
- Fortify導入&カスタム認証(
Fortify::authenticateUsing)済み - Laravel BreezeやJetstream等のUIパッケージは無し(Bladeを自作する想定)
1. ルーティングの確認
FortifyはAPIベース認証ですが、config/fortify.php の 'views' => true, を有効にしておくとBladeビューを利用できます。
// config/fortify.php
'views' => true,
2. Bladeでログインフォームを作成
resources/views/auth/login.blade.php を作成します。
@extends('layouts.app')
@section('content')
<div class="container">
<h2>カスタムログイン</h2>
@if(session('error'))
<div style="color: red">{{ session('error') }}</div>
@endif
<form method="POST" action="{{ route('login') }}">
@csrf
<div>
<label for="user_code">ユーザーコード:</label>
<input type="text" name="user_code" id="user_code" value="{{ old('user_code') }}" required autofocus>
</div>
<div>
<label for="password">パスワード:</label>
<input type="password" name="password" id="password" required>
</div>
<button type="submit">ログイン</button>
</form>
</div>
@endsection
3. ログイン画面へのルート
routes/web.php に以下を追加(既定でFortifyが/loginルートを用意していますが、明示的にBladeを返したい場合は上書きも可能です)
use Illuminate\Support\Facades\Route;
Route::get('/login', function () {
return view('auth.login');
})->name('login')->middleware('guest');
4. 認証失敗時のエラーハンドリング
app/Providers/FortifyServiceProvider.php の boot メソッドで、失敗時にリダイレクト&エラー表示できるようにします。
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
public function boot()
{
Fortify::authenticateUsing(function (Request $request) {
// ...カスタム認証処理...
});
// 認証失敗時の挙動カスタマイズ
app('router')->post('login', function (Request $request) {
$credentials = $request->only('user_code', 'password');
if (Auth::attempt(['user_code' => $credentials['user_code'], 'password' => $credentials['password']])) {
$request->session()->regenerate();
return redirect()->intended('/dashboard');
}
return Redirect::back()->withInput()->with('error', 'ユーザーコードまたはパスワードが正しくありません');
})->middleware(['guest']);
}
※ Fortifyのコアをオーバーライドしない場合は、コントローラやカスタムリダイレクトもOK。
5. ログイン後のリダイレクト
FortifyServiceProvider の redirectTo をカスタマイズ可能です。または、config/fortify.php の home を編集します。
// config/fortify.php
'home' => '/dashboard',
6. ダッシュボード画面の作成例
@extends('layouts.app')
@section('content')
<div class="container">
<h2>ダッシュボード</h2>
<p>ようこそ、{{ Auth::user()->name }}さん!</p>
<form method="POST" action="{{ route('logout') }}">
@csrf
<button type="submit">ログアウト</button>
</form>
</div>
@endsection
7. まとめ
- FortifyでAPI認証でも、BladeビューでUIを柔軟に作成可能
- カスタム入力項目(ユーザーコード等)もBladeフォームに自由に追加できる
- 認証失敗時のエラー表示やリダイレクトもカスタマイズしやすい