19
22

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 5 years have passed since last update.

Laravel5.5で未認証時にリダイレクトさせる処理

Last updated at Posted at 2018-05-27

環境

  • Laravel5.5
  • multi auth

やりたいこと

Multi auth を使っている前提で、未認証時にユーザ・管理者それぞれのログインページにリダイレクトさせたい。

5.4 までは app/Exceptions/Handler.php に直書きされていた

5.4 では、app/Exceptions/Handler.php に unauthenticated メソッドがありました。

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    .
    .
    .
    /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect()->guest(route('login'));
    }
}

これが、5.5 では初期状態では書かれていません。
vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php
こちらにあるようです。
どっちにしても、 app/Exceptions/Handler.php 内で unauthenticated をオーバーライドします。

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    .
    .
    .
    /**
     * 認証していない場合にガードを見てそれぞれのログインページへ飛ばず
     *
     * @param \Illuminate\Http\Request $request
     * @param AuthenticationException $exception
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
     */
    public function unauthenticated($request, AuthenticationException $exception)
    {
        if($request->expectsJson()){
            return response()->json(['message' => $exception->getMessage()], 401);
        }

        if (in_array('admin', $exception->guards())) {
            return redirect()->guest(route('admin.login'));
        }

        return redirect()->guest(route('user.login'));
    }
}

参考

▼Laravel 5.5 change unauthenticated login redirect url
https://stackoverflow.com/questions/45340855/laravel-5-5-change-unauthenticated-login-redirect-url
▼[Laravel] 5.3でMulti-Authを使う
http://www.84kure.com/blog/2016/06/06/laravel-5-3%E3%81%A7multi-auth%E3%82%92%E4%BD%BF%E3%81%86/

19
22
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
19
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?