8
3

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.

Laravelのマルチauthで認証済みの独自定義ユーザを取得する方法・Nuxt SSR時のログイン状態維持

Last updated at Posted at 2019-10-23

php artisan make:authで作成できるユーザの認証状態はAuth::user()で取得できますが、
マルチauthでの独自に定義したユーザは上記の方法では認証状態を取得することはできません。

そこで、認証済み独自ユーザを取得する方法をadminという独自ユーザを例に解説します。
早速ですが、以下コードになります。

Auth::guard('admin')->user()

Authファサードのguardメソッドを使って、使用したい独自ユーザのガードを指定することで、
マルチauthでの認証済の独自ユーザの取得を実現しています。

今回はadminを指定しているので、認証済adminの取得になります。

利用例(Laravel × Nuxt)

実際に使うときは、routesのapi.phpなどで以下のように利用しています。

/routes/api.php
Route::get('/admin', function () {
  return Auth::guard('admin')->user();
})->name('admin');

Nuxtでログイン状態の維持のために以下のように使えます。

/store/index.js
export const actions = {
  async nuxtServerInit ({ commit }, { app }) {
    await app.$axios.$get('/admin')
      .then(admin => commit('auth/setAdmin', admin))
      .catch(() => commit('auth/setAdmin', null))
  }
}

SSR時のログインチェックを行わせることで、Nuxt側で認証をstoreにセットして、ログイン状態を維持できるわけですね。

LaravelとNuxtでの認証周りの開発の参考になれば幸いです。

マルチauth作成で参考にさせていただいたページ

8
3
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
8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?