Change Auth models on the fly

I used config::set('auth.model','App\Fblogin') and selected config::get('auth.model'); The value seems to be perfectly updated, but when I try Auth::logInUsingId() , it looks like it still uses the default value of App\User . So what can I do, can I use App\Fblogin on my controller?

+5
source share
2 answers

If you are using Laravel 5.1.11 or later, use this:

 auth()->getProvider()->setModel(App\Fblogin::class); 

If you cannot / will not update, I am afraid that there is no easy way to achieve this.

Model resolved using EloquentUserProvider . The model class used is specified in the constructor, which cannot be changed at run time, since the property is protected .

You can either extend EloquentUserProvider , or trick and install it:

 function set_auth_model($model) { $closure = (function ($model) { $this->model = $model; }); $closure = $closure->bindTo(Auth::getProvider()); $closure($model); } set_auth_model(App\Fblogin::class); 

But really ... just upgrade.

+5
source

It may be possible, but you will have to try it. You can configure your own Auth driver, which simply extends the standard larvel auth driver, but modifies it a bit. You can do this through a provider, for example. In the provider download method, you say:

  $this->app['auth']->extend('my-auth', function ($app) { return new Guard( new MyUserProvider($app['hash']), $app->make('session.store') ); }); 

Please note that we no longer pass the model through the constructor. We will handle it differently. Your class MyUserProvider extends EloquentUserProvider. We override the createModel method to our own version, which instead of using the constructed model name gets the model name at run time.

 class MyUserProvider extends EloquentUserProvider { public function __construct(HasherContract $hasher) { $this->hasher = $hasher; } public function createModel() { $class = app()->config->get('auth.model'); return new $class; } } 

I really have not tried to figure out if this works, but you can probably use this using this method.

+1
source

All Articles