[Laravel 8.x] 不在 middleware 判斷是否需要登入後才能看

平常要讓 route 登入後才能使用,會直接使用 auth middleware,如果未登入該 middleware 會導向登入頁進行登入後再回來,在這種情況下程式不會進入 controller。

如果想在 controller 判斷登入才可以使用,未登入也能導向登入頁再回來該怎麼做呢?

稍微爬一下 auth middleware 程式就可以得到答案,裡面有一個 function 在處理未登入要做什麼事情(如下↓),可以看到裡面就只是簡單拋出 AuthenticationException。
  1. /**
  2. * Handle an unauthenticated user.
  3. *
  4. * @param \Illuminate\Http\Request $request
  5. * @param array $guards
  6. * @return void
  7. *
  8. * @throws \Illuminate\Auth\AuthenticationException
  9. */
  10. protected function unauthenticated($request, array $guards)
  11. {
  12. throw new AuthenticationException(
  13. 'Unauthenticated.', $guards, $this->redirectTo($request)
  14. );
  15. }
所以我們可以學他,如果未登入就拋出 AuthenticationException (如下↓),三個參數分別是訊息內容、guards、導向網址。
  1. use Auth;
  2. use Illuminate\Auth\AuthenticationException;
  3. use Illuminate\Http\Request;
  4.  
  5. public function show(Request $request)
  6. {
  7. if (!Auth::check()) {
  8. throw new AuthenticationException(
  9. 'Unauthenticated.', [null], route('login')
  10. );
  11. }
  12.  
  13. ...
  14. }
沒想到這麼簡單,真是出乎我的意料。

留言