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 その4 Auth情報を取得してViewやControllerで使用する

Posted at

はじめに

前回までの記事で、カスタム認証やUI連携、パスワードリセット・メール認証のカスタマイズを紹介しました。
今回は「Laravel 12 + Fortify」の認証済みユーザー情報(Auth情報)をBladeビューやコントローラで取得・活用する基本パターンをまとめます。


1. コントローラでAuth情報を取得する

1-1. 現在のユーザー情報

use Illuminate\Support\Facades\Auth;

$user = Auth::user(); // 認証済みユーザー(Userモデルインスタンス) or null

1-2. IDのみ取得

$userId = Auth::id(); // 認証済みユーザーのID or null

1-3. 属性へアクセス

if ($user) {
    $userCode = $user->user_code;
    $email = $user->email;
}

2. BladeビューでAuth情報を使う

2-1. Bladeのグローバル変数

BladeではAuthファサードまたはauth()ヘルパを使うことで、認証ユーザー情報にアクセスできます。

ようこそ、{{ Auth::user()->name }}さん!

または

@auth
    <p>こんにちは、{{ auth()->user()->name }}さん!</p>
@endauth

@guest
    <p>ログインしてください。</p>
@endguest

3. ミドルウェアでの利用

3-1. 認証チェック

コントローラやルートでauthミドルウェアを付与していれば、Auth::user()は常に「認証済みユーザー」を返します。

Route::get('/dashboard', function () {
    $user = Auth::user();
    // ...処理
})->middleware('auth');

4. APIでのAuth情報取得

APIルート(routes/api.php)でFortifyのトークン認証を使っている場合も、auth:sanctumauth:apiミドルウェアを通せばAuth::user()が利用可能です。

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

5. よくある応用例

5-1. ログインユーザーの情報をViewに渡す

public function showDashboard()
{
    $user = Auth::user();
    return view('dashboard', compact('user'));
}

Blade内で

<p>あなたのユーザーコード: {{ $user->user_code }}</p>

5-2. 条件分岐

@if(Auth::check())
    <!-- ログイン時の表示 -->
@else
    <!-- 未ログイン時の表示 -->
@endif

まとめ

  • Fortifyで認証したユーザー情報は、Auth::user()auth()->user() でコントローラ・ビューどちらでも簡単に取得可能
  • Bladeの@auth/@guestディレクティブや、コントローラでの属性アクセスなども活用できる
  • APIやSPAでも、ミドルウェア経由で同様に取得できる

参考

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?