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?

More than 1 year has passed since last update.

ログイン時にユーザーIDを遷移先に渡す

Posted at

はじめに

個人開発メモ📝
認証後、ユーザーIDを遷移先に渡す方法を備忘録として残します。

laravel側のコントローラーで、ユーザーIDを返す

// 検証後のデータを認証
if(Auth::attempt($loginUser)) {
  // ユーザー情報を取得
  $user = Auth::user();
  return response()->json([
   'userId' => $user->id,
   'message' => '認証成功',
   'redirectTo' => '/calender',
  ], 200);
};

Auth::user()は、ユーザー情報のオブジェクトを返しているので、$user内にはユーザー情報が入っています。
$user->idとすることでユーザー情報のオブジェクトからidを取得しています。

フロントでレスポンスデータを受け取り、ローカルストレージにIDを保存する

const handleSubmit = async(event) => {
  event.preventDefault();
  try {
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(loginForm)
    });
    const responseLoginData: loginUserData = await response.json();
      // ユーザーIDをローカルストレージに保存し、カレンダーページへ遷移
      if(responseLoginData) {
        localStorage.setItem('userId', responseLoginData.userId.toString());
        window.location.href = responseLoginData.redirectTo;
      }
    } catch(error) {
      console.log(error);
  };
};

クライアント側に保存されるので注意が必要ですが、今回はユーザーIDのみなのでローカルストレージに保存しました。

遷移先でユーザーIDの確認

// ローカルストレージに保存されているIDの確認
const userId = localStorage.getItem('userId');
console.log('保存されていたユーザーID:', userId);

スクリーンショット 2023-11-30 6.16.24.png

遷移先でユーザーIDの確認ができました。
今度はこのIDを使用して、そのユーザーのデータを表示できるようにしていきます。

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?