Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend Laravel's Auth Guard class?

I'm trying to extend Laravel's Auth Guard class by one additional method, so I'm able to call Auth::myCustomMethod() at the end.

Following the documentation section Extending The Framework I'm stuck on how to exactly do this because the Guard class itself doesn't have an own IoC binding which I could override.

Here is some code demonstrating what I'm trying to do:

namespace Foobar\Extensions\Auth;

class Guard extends \Illuminate\Auth\Guard {

    public function myCustomMethod()
    {
        // ...
    }

}

Now how should I register the extended class Foobar\Extensions\Auth\Guard to be used instead of the original Illuminate\Auth\Guard so I'm able to call Auth::myCustomMethod() the same way as e.g. Auth::check()?

One way would be to replace the Auth alias in the app/config/app.php but I'm not sure if this is really the best way to solve this.

BTW: I'm using Laravel 4.1.

like image 298
Holger Weis Avatar asked Dec 20 '13 10:12

Holger Weis


1 Answers

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`.

like image 140
David Barker Avatar answered Sep 21 '22 09:09

David Barker