且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel 5.2 需要一个实现默认身份验证驱动程序/“多重身份验证"的示例.现在需要做很多工作

更新时间:2023-09-24 13:41:22

创建两个新模型:AppAdminAppUser.更新config/auth.php:

Create two new models: AppAdmin and AppUser. Update config/auth.php:

return [
    'defaults' => [
        'guard' => 'user',
        'passwords' => 'user',
    ],
    'guards' => [
        'user' => [
            'driver' => 'session',
            'provider' => 'user',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admin',
        ],
    ],
    'providers' => [
        'user' => [
            'driver' => 'eloquent',
            'model' => 'AppUser',
        ],
        'admin' => [
            'driver' => 'eloquent',
            'model' => 'AppAdmin',
        ],
    ],
    'passwords' => [
        'user' => [
            'provider' => 'user',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'admin' => [
            'provider' => 'admin',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ]
    ]
];

在 kernel.php 中

In kernel.php

    protected $middleware = [
        IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class,
        IlluminateSessionMiddlewareStartSession::class,
        IlluminateViewMiddlewareShareErrorsFromSession::class
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,

            //AppHttpMiddlewareVerifyCsrfToken::class,
        ],

        'api' => [
            'throttle:60,1',
        ],
    ];

在Route.php中设置下面的代码和测试

and in Route.php set below code and test

    Route::get('/login', function() {
        $auth = auth()->guard('admin');

        $credentials = [
            'email' =>  'admin@gmail.com',
            'password' =>  'password',
        ];

        if ($auth->attempt($credentials)) {
            return redirect('/profile');
        } 
    });



    Route::get('/profile', function() {
            if(auth()->guard('admin')->check()){
                 print_r(auth()->guard('admin')->user()->toArray());
            } 

            if(auth()->guard('user')->check()){
                print_r(auth()->guard('user')->user()->toArray());
            }
        });