How to extend the Laravel Auth Guard class?

I am trying to extend the Laravel Auth Guard class with one additional method, so I can call Auth::myCustomMethod() at the end.

Following the extension section of the documentation, I focused on how to do this, because the Guard class itself does not have its own IoC binding , which I could override.

Here is the code that demonstrates 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 , which will be used instead of the original Illuminate\Auth\Guard , so I can call Auth::myCustomMethod() in the same way as, for example, Auth::check() ?

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

By the way: I am using Laravel 4.1.

+6
source share
2 answers

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

I recommend creating your own service provider or directly extending the Auth class in one of the startup files (for example, start/global.php ).

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

This is a good tutorial that you can use for a better understanding.

There is another method that you could use. This will be due to the distribution of one of the current suppliers, such as Eloquent.

 class MyProvider extends Illuminate\Auth\EloquentUserProvider { public function myCustomMethod() { // Does something 'Authy' } } 

Then you can simply extend auth as described 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') ); }); 

After you injected the code, you would modify the driver in the auth.php configuration file to use 'nonDescriptAuth`.

+8
source

The only way to add (as well as replace existing functions) is to create a copy of the Guard.php file in your project and add to app / start / global.php

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

Of course, this is an ugly method, but I spent more than an hour to check all the possibilities [how to change things stored in Session by Auth] and it always ends up with an error: ... _contruct of the HSGuard class requires that the first parameter be "UserProviderInterface" and received "EloquentUserProvider" ...

-7
source

All Articles