How to extend Laravel's Auth Guard class?
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`.
Holger Weis
Updated on June 25, 2022Comments
-
Holger Weis almost 2 years
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 originalIlluminate\Auth\Guard
so I'm able to callAuth::myCustomMethod()
the same way as e.g.Auth::check()
?One way would be to replace the
Auth
alias in theapp/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.
-
Holger Weis over 10 yearsThanks for your answer David! I was hoping there is a simpler method than creating a own UserProvider to extend the Guard class. I will wait some time to see if there are other suggestions.
-
David Barker over 10 years@HolgerWeis I've added in a simple method to extend Auth with the current Eloquent driver with an extension. The
Auth::extend
code should work as is.