Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Auth's Model on the fly

I used config::set('auth.model','App\Fblogin') and fetched config::get('auth.model'); It seems to update the value just fine, but when I try to Auth::logInUsingId() it seems like it's still using the default App\User. So what do I do so I can use the App\Fblogin on my controller?

like image 991
Mouse Hello Avatar asked Aug 07 '15 14:08

Mouse Hello


2 Answers

If you're using Laravel 5.1.11 or higher, use this:

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

If you can't/won't upgrade, I'm afraid there's no easy way to achieve this.

The model is resolved through the EloquentUserProvider. The model class used is set in the constructor, which cannot be changed at runtime because the property is protected.

You can either extend the EloquentUserProvider, or you can cheat and set 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.

like image 73
Joseph Silber Avatar answered Sep 30 '22 18:09

Joseph Silber


This may be possible but you'd have to try this out. You can set up your own Auth driver, which simply extends the default laravel auth driver but modifies it a bit. You can do this through a provider for instance. In the boot method of the provider you'd say:

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

Note we're no longer passing the model through the constructor. We'll handle that differently.Your MyUserProvider class extends EloquentUserProvider. We override the createModel method to our own version, which instead of using the constructed model name, gets the model name during runtime.

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 havent actually tried to see if this works, but you can probably get this to work using this method.

like image 42
Cor Bosman Avatar answered Sep 30 '22 19:09

Cor Bosman