简体   繁体   中英

Multi provider relational user table in laravel

I am new in laravel and trying to create an auth system where user can login/register using multiple providers and whenever user logins using any of providers the user avatar and profile data must be shown accordingly. When using Auth::user()->providers the result is array of all registered providers for that user.

What I want is to fetch only provider data for current login method (ie local account, facebook account provider, google account provider etc) so I can show data from that exact provider for user.

User.php

...
    public function providers()
    {
        return $this->hasMany("App\UserProvider");
    }
...

UserProvider.php

class UserProvider Extends Model
{
    protected $table = 'user_providers';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'provider', 'provider_id','avatar_url', 'token', 'token_secret',
    ];

}

Please let me know if I am on the right way or is there any other way to do this. Thanks!

You can use your relation to build a query

$provider = Auth::user()->providers()->where('provider', 'facebook')->first();

This will return single UserProvider class object

You could also include a boolean column in your user_providers table to know which of the providers is the last used (so this will be the current login method). Let's call this column is_current .

So, when a user access the system, you update the login method setting this field to true . You can do this by overriding the authenticated() method of the app\\Http\\Controllers\\LoginController controller:

# app\Http\Controllers\LoginController.php

protected function authenticated(Request $request, $user)
{
    Auth::user()
          ->providers()
          ->where('provider', $request->provider) // Change this to make it work
          ->update('is_current', true);
}

This way, you can access your current login method wherever you want, doing this:

Auth::user()->providers()->whereTrue('is_current')->first();

Of course, you could make an accessor in your model to shorten this:

# User.php

public function getCurrentProviderAttribute()
{
    return $this->providers()->where('is_current', true)->first();
}

So now, you can do simply:

Auth::user()->current_provider;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM