109
92

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel 認証済みユーザーの取得方法

Last updated at Posted at 2021-04-05

公式ドキュメント

環境

  • PHP: 8.1.12
  • Laravel: 9.43.0

認証済みユーザー取得

Laravelで認証済みユーザーを取得する方法がいくつかあるのでご紹介します。

Authファサード

use Illuminate\Support\Facades\Auth;

// 現在認証しているユーザーを取得
$user = Auth::user();

// 現在認証しているユーザーのIDを取得
$id = Auth::id();

authヘルパー

// 現在認証しているユーザーを取得
$user = auth()->user();

// 現在認証しているユーザーのIDを取得
$id = auth()->id();

Requestインスタンス(メソッドインジェクション)

app/Http/Controllers/FlightController.php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

final class FlightController extends Controller
{
    /**
     * @param Request $request
     * @return Response
     */
    public function update(Request $request): Response
    {
        $user = $request->user();

        // ...
    }
}

LaravelのFormRequestもRequestを継承しているので、同様に user() メソッドを使用できます。

関連記事

109
92
2

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
109
92

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?