Laravel カスタムユーザープロバイダー

ショコラ
ショコラ

Laravel カスタムユーザープロバイダー

DBに保存しない、WEBで認証するユーザーを使用することになりました。

もっさん先輩
もっさん先輩

① app/Auth/CustomUserProvider.php を作成する。

<?php
namespace App\Auth;

use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Auth\Authenticatable;

class CustomUserProvider implements UserProvider
{
    /**
     * Retrieve a user by their unique identifier.
     *
     * @param  mixed  $identifier
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveById($identifier)
    {
        // ユーザーの検索ロジックを実装する
    }

    /**
     * Retrieve a user by the given credentials.
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        // 認証に使用するユーザーを検索し、見つかったら返す
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $credentials
     * @return bool
     */
    public function validateCredentials(Authenticatable $user, array $credentials)
    {
        // ユーザーの認証情報を検証する
    }

    // 以下は、ユーザープロバイダーのインターフェースの他のメソッドを実装することもできますが、
    // この例では最小限の実装としています
}

② app/Providers/CustomUserProviderServiceProvider.php を作成する。

<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Auth\CustomUserProvider;

class CustomUserProviderServiceProvider extends ServiceProvider
{
  public function boot()
  {
   \Auth::provider('custom', function ($app, array $config) {
     // カスタム認証ロジックを実装
     return new CustomUserProvider();
   });
  }
}

③ config/auth.php カスタムプロバイダーを読み込ませる。

'providers' => [
    // 他のプロバイダー...
    App\Providers\CustomUserProviderServiceProvider::class,
],
'providers' => [
    'users' => [
        'driver' => 'custom',
        'model' => App\Models\User::class,
    ],
],

以上

Scroll to Top