How to extend Laravel's Auth Guard class?

那年仲夏 提交于 2019-12-04 05:21:54

I would create my own UserProvider service that contain the methods I want and then extend Auth.

I recommend creating your own service provider, or straight up extending the Auth class in one of the start files (eg. start/global.php).

Auth::extend('nonDescriptAuth', function()
{
    return new Guard(
        new NonDescriptUserProvider(),
        App::make('session.store')
    );
});

This is a good tutorial you can follow to get a better understanding

There is another method you could use. It would involve extending one of the current providers such as Eloquent.

class MyProvider extends Illuminate\Auth\EloquentUserProvider {

    public function myCustomMethod()
    {
        // Does something 'Authy'
    }
}

Then you could just extend auth as above but with your custom provider.

\Auth::extend('nonDescriptAuth', function()
{
    return new \Illuminate\Auth\Guard(
        new MyProvider(
            new \Illuminate\Hashing\BcryptHasher,
            \Config::get('auth.model')
        ),
        \App::make('session.store')
    );
});

Once you've implemented the code you would change the driver in the auth.php config file to use 'nonDescriptAuth`.

Only way to add (and also replace existing functions) is to create copy of Guard.php file in your project and in app/start/global.php add:

require app_path().'/models/Guard.php';

Of course it's ugly method, but I spent over hour to test all possibilities [how to change things stored in Session by Auth] and it always end with error: ... _contruct of class HSGuard requires first parameter to be 'UserProviderInterface' and get 'EloquentUserProvider' ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!