Как изменить модель аутентификации в Laravel - PullRequest
1 голос
/ 02 апреля 2019

Мне нужно изменить модель пользователя по умолчанию в моей модели Laravel Application на Admin.Я следовал руководству, данному в изменить модель аутентификации в Laravel 5.3

, модель администратора должна выполнить аутентификацию, зарегистрировать и сбросить пароль.Это то, что я сделал до сих пор.

После выполнения php artisan make:auth я создал Admin.php модель

namespace Modules\Admin\Entities;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable
{
    use Notifiable;
    protected $fillable = ['name','email','password'];
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Это config/auth.php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'admins',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => \Modules\Admin\Entities\Admin::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

и этоRegisterController.php

namespace App\Http\Controllers\Auth;

use Modules\Admin\Entities\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:admins'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return Admin::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
}

Этот код создает пользователя в таблице admins, но при попытке войти в систему выдает следующую ошибку:

Аргумент 2переданный в Illuminate \ Auth \ SessionGuard :: __ construct () должен быть экземпляром Illuminate \ Contracts \ Auth \ UserProvider, значение NULL которого вызывается в ... \ vendor \ laravel \ framework \ src \ Illuminate \ Auth \ AuthManager.php onстрока 125

Я не могу понять, почему эта ошибка происходит.

Ответы [ 2 ]

1 голос
/ 02 апреля 2019

Все драйверы аутентификации имеют провайдера пользователя.

Это определяет, каким образом пользователи фактически извлекаются из вашей базы данных или других механизмов хранения, используемых этим приложением для сохранения данных вашего пользователя.

Изменение вашего config/auth.phpтакой файл:

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ]
]
1 голос
/ 02 апреля 2019

Измените свой код на config/auth.php:

'web' => [
        'driver' => 'session',
        'provider' => 'admins',
 ],

на:

'web' => [
        'driver' => 'session',
        'provider' => 'users',
 ],
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...