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のAuth::id()とAuth::user()の使い方のまとめ

Posted at

はじめに

Laravelでログイン中のユーザー情報を取得する際によく使うのが、

Auth::id()
Auth::user()
Auth::user()->name

などの記述です。

この記事では、それぞれがどういう意味を持ち、どんな場面で使うのかを、初心者向けにまとめていきます。

①Auth::id()の意味と使い方

$userId = Auth::id();
  • ログイン中のユーザーの「ID(数値)」だけを取得します。
  • 戻り値はintまたは、null(未ログインの場合)。

使いどころ:

  • ログインユーザーが作成したデータに「user_id」を紐づけるとき:
$post = new Post();
$post->title = '新しい投稿';
$post->user_id = Auth::id(); // 現在のログインユーザーID
$post->save();

②Auth::user()の意味と使い方

$user = Auth::user()
  • ログイン中のユーザー情報をまるごと取得できます。
  • 戻り値はUserモデルのインスタンス(ログインしていないときはnull)。

例:

$user = Auth::user()
echo $user->name;
echo $user->email;

Bladeテンプレートでもよく使います:

<p>こんにちは、{{ Auth::user()->name }} さん!</p>

③Auth::user()->〇〇で各種情報を取得

Auth::user()で取得したUserモデルのプロパティで直接参照できます。

よく使うプロパティ例:
IMG_7747.jpeg

例:

$name = Auth::user()->name;
$email = Auth::user()->email;

④未ログイン時のエラーに注意!

ログインしてない状態でAuth::user()->nameのように書くと...

Error: Tryping to get property 'name' of non-object

というエラーが発生します。

対策:

@if(Auth::check())
    <p>ようこそ、{{ Auth::user()->name }} さん!</p>
@else
    <p>ログインしてください。</p>
@endif

もしくは:

$name = optional( Auth::user())->name ?? 'ゲスト';

⑤Auth::check()もセットで覚えておこう

if(Auth::check()) {
   // ログイン中の処理
}
  • Auth::check()は「ユーザーがログインしているかどうか」を判定する関数です。

⑥まとめ

IMG_7748.jpeg

Laravelの認証システムは非常に柔軟で、こうした関数を使えば簡単に「ログインユーザーに紐づけた処理」ができます!

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?