LoginSignup
2
0

More than 1 year has passed since last update.

Laravel FortifyのレスポンスをJSONで返す方法

Last updated at Posted at 2023-01-15

背景

通常、Laravel Fortifyを使用してログインに成功すると、Fortifyはアプリケーションのfortify.php内の home設定オプションで設定した URI にリダイレクトします。ログイン要求がXHR要求であった場合、200HTTPレスポンスを返します。

ただしSPAの構成などをとっている場合は、レスポンスをJSON形式で返したいこともあリます。そんな時に行う設定を備忘録がてら記載していきます。

FortifyのレスポンスをJSONで返す方法

早速結論ですが、App\Providers\FortifyServiceProvider.php内のregisterメソッドに下記コードのように実装します。返すJSONの構造は適宜変更してください。

App\Providers\FortifyServiceProvider.php
use Laravel\Fortify\Contracts\LogoutResponse;

public function register()
{
    $this->app->instance(LogoutResponse::class, new class implements LogoutResponse {
        public function toResponse($request)
        {
            // JSONの構造は適宜変更してください。
            return response()->json([
              'code' => 200,
              'user' => $request->user()
            ]);
        }
    });
}

これでログイン成功時にはJSONが返却されるようになりましたが、ログイン済みの状態でAPIを叩いた場合はHOME画面にリダイレクトされてしまうので、以下のようにApp/Http/Middleware/RedirectIfAuthenticated.phpのコードを修正します。

App/Http/Middleware/RedirectIfAuthenticated.php
+ use Illuminate\Http\JsonResponse;

class RedirectIfAuthenticated
{
    public function handle(Request $request, Closure $next, ...$guards): JsonResponse
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
-               return redirect(RouteServiceProvider::HOME);
+               return response()->json([
+                   'message' => '既に認証済みです。'
+               ], 200);
            }
        }

        return $next($request);
    }
}

これでログイン成功時、ログイン済みの状態でAPIを叩いた場合どちらでもレスポンスにJSONが返却されるようになります。

終わりに

簡単ですが、以上になります。
他の詳しい内容は下記Documentにも記載されているので、よければご覧ください。
https://laravel.com/docs/9.x/fortify

2
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
2
0