Laravel Socialite 的名字和姓氏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32407604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:18:29  来源:igfitidea点击:

Laravel Socialite first and last name

phplaravellaravel-5.1

提问by junkystu

I'm adding social authentication to an application using Laravel's Socialite. I can retrieve the full name but not the first and last names separately. After the callback happens and Socialite is handling it, the user is retrieved successfully. If I am to dump the user I get back from $user = this->social->driver('facebook')->user();I get the following:

我正在使用 Laravel 的 Socialite 向应用程序添加社交身份验证。我可以检索全名,但不能分别检索名字和姓氏。回调发生后,Socialite 正在处理,成功检索到用户。如果我要转储用户,我会$user = this->social->driver('facebook')->user();得到以下信息:

object(Laravel\Socialite\Two\User)#459 (8) {
     ["token" ]=> string(209) "{token}"
     ["id"] => string(17) "{socialID}"
     ["nickname"] => NULL
     ["name"] => string(14) "{Full Name}"
     ["email"] => string(19) "{Email address}"
     ["avatar"] => string(69) "https://graph.facebook.com/v2.4/{socialID}/picture?type=normal"
     ["user"] => array(6) {
        ["first_name"] => string(6) "{First name}"
        ["last_name"] => string(7) "{Last mame}"
        ["email"] => string(19) "{Email address}"
        ["gender"] => string(4) "male"
        ["verified"] => bool(true)
        ["id"] => string(17) "{socialID}"
    }
    ["avatar_original"] => string(68) "https://graph.facebook.com/v2.4/{socialID}/picture?width=1920"

}

}

I can obtain the full name or email via $user->nameor $user->emailhowever, I can not get the separate first and last names. I have tried $user->first_nameas well as trying to dump the $user->userarray but all I see is undefined property errors.

我可以通过以下方式获得全名或电子邮件,$user->name或者$user->email,我无法获得单独的名字和姓氏。我已经尝试$user->first_name并尝试转储$user->user数组,但我看到的只是未定义的属性错误。

I do not want to do something weird like extract it from the full name when the separate first and last name are clearly there as it can get ugly when middle names are present.

我不想做一些奇怪的事情,比如当单独的名字和姓氏明显存在时从全名中提取它,因为当中间名存在时它会变得丑陋。

I have Googled my way around and weirdly, nobody came across this issue. Am I missing something from the docs? Any suggestions on how to retrieve the first and last name from the userarray are greatly appreciated.

我在谷歌上搜索了一下,奇怪的是,没有人遇到过这个问题。我从文档中遗漏了什么吗?user非常感谢有关如何从数组中检索名字和姓氏的任何建议。

采纳答案by koala_dev

According to the dump of the $uservar you should be able to access the name values by doing:

根据$uservar的转储,您应该能够通过执行以下操作来访问名称值:

$user->user['first_name']and $user->user['last_name']

$user->user['first_name']$user->user['last_name']

回答by Richard Torcato

I've found that sometimes the user object won't contain the first and last names unless you specify you need those fields.

我发现有时用户对象不会包含名字和姓氏,除非您指定需要这些字段。

//get the driver and set desired fields
$driver = Socialite::driver('facebook')
                ->fields([
                    'name', 
                    'first_name', 
                    'last_name', 
                    'email', 
                    'gender', 
                    'verified'
                ]);
// retrieve the user
$user = $driver->user();

then you can get the first name and last name like this

然后你可以像这样得到名字和姓氏

$user->user['first_name'] and $user->user['last_name']

Other stuff you can ask for:

您可以要求的其他内容:

https://developers.facebook.com/docs/graph-api/reference/user/

https://developers.facebook.com/docs/graph-api/reference/user/

for google plus:

对于谷歌加:

$user->firstname = $user->user['name']['givenName'];
$user->lastname = $user->user['name']['familyName'];

回答by Haritsinh Gohil

You can also use offsetGet()method which is defined in AbstractUserclass of socialitepackage, which returns $this->user[$offset];so using it you can get first name and last name,

您还可以使用offsetGet()在包AbstractUser类中定义的方法socialite,该方法返回$this->user[$offset];因此使用它您可以获得名字和姓氏,

but for facebookand googleit differs because of their different response so i have given code below for both facebook and google.

但是对于facebookgoogle,它的不同是因为它们的响应不同,所以我在下面给出了 facebook 和 google 的代码。

For GOOGLE & FACEBOOK

适用于 GOOGLE 和 FACEBOOK

$providerUser = Socialite::driver($provider)->user(); // $provider can be facebook, google etc.

switch($provider){
   case 'facebook':
      $first_name = $providerUser->offsetGet('first_name');
      $last_name = $providerUser->offsetGet('last_name');
      break;

   case 'google':
      $first_name = $providerUser->offsetGet('given_name');
      $last_name = $providerUser->offsetGet('family_name');
      break;

 // You can also add more provider option e.g. linkedin, twitter etc.

   default:
      $first_name = $providerUser->getName();
      $last_name = $providerUser->getName();
}

$user = User::create([
                'first_name' => $first_name,
                'last_name' => $last_name,
                'email' => $providerUser->getEmail(),
                'image' => $providerUser->getAvatar(),
            ]);

回答by nlagdhir

In linkedin you can get first and last name from provider like this.

在linkedin中,您可以像这样从提供者那里获得名字和姓氏。

$linkedinUser = $this->socialite->driver('linkedin')->user());

$attributes = [
        'first_name' => $linkedinUser->user['firstName'],
        'last_name' => $linkedinUser->user['lastName'],
        'email' => $linkedinUser->email,
        'avatar' => $linkedinUser->avatar,
        'linkedin_id' => $linkedinUser->id
    ];

回答by Sameer

And you could simply do:

你可以简单地做:

$NameArray = explode(' ',$user->getName());
$First_name = $NameArray[0];
$Last_name = $NameArray[1];

回答by christostsang

After coming against the same issue myself, i noticed that all social networks i used for registration/login (Facebook, Twitter, Google+, Github) send back a "name" attribute. This attribute can either be empty (if the user hasn't added any information) or carry a value.

在我自己遇到同样的问题后,我注意到我用于注册/登录的所有社交网络(Facebook、Twitter、Google+、Github)都发回了一个“名称”属性。此属性可以为空(如果用户未添加任何信息)或带有值。

What i did, was to create a method (getFirstLastNames()) that will get that "name" value and break it into first_nameand last_nameby exploding them when a space or multiple spaces is detected. Then i use them to populate my users table:

我所做的是创建一个方法 (getFirstLastNames()),该方法将获取该“ name”值,并在检测到一个空格或多个空格时将它们分解为first_namelast_name。然后我用它们来填充我的用户表:

protected function getFirstLastNames($fullName)
{
    $parts = array_values(array_filter(explode(" ", $fullName)));

    $size = count($parts);

    if(empty($parts)){
        $result['first_name']   = NULL;
        $result['last_name']    = NULL;
    }

    if(!empty($parts) && $size == 1){
        $result['first_name']   = $parts[0];
        $result['last_name']    = NULL;
    }

    if(!empty($parts) && $size >= 2){
        $result['first_name']   = $parts[0];
        $result['last_name']    = $parts[1];
    }

    return $result;
}

The $fullName variable is:

$fullName 变量是:

Socialite::driver($provider)->getName();

For this implementation i assume that:

对于这个实现,我假设:

  1. No matter how many names the user has, i will use the first part of the string as the first_nameand the second one as the last_name. [if my name is POPPY PETAL EMMA ELIZABETH DEVERAUX, then i will use POPPY as first_name and PETAL as last_name. The rest will be ignored]. If the "name" attribute comes back empty or with one name, then i insert NULL into the users table where i get no value.
  2. If the user has used multiple spaces while separating the names (or before and after the names), this method will remove them and keep only the strings.
  1. 无论用户有多少个名字,我都会将字符串的第一部分用作first_name,将第二部分用作last_name。[如果我的名字是 POPPY PETAL EMMA ELIZABETH DEVERAUX,那么我将使用 POPPY 作为 first_name 和 PETAL 作为 last_name。其余的将被忽略]。如果“名称”属性返回空或具有一个名称,那么我将 NULL 插入到用户表中,在那里我没有得到任何值。
  2. 如果用户在分隔名称时(或名称前后)使用了多个空格,则此方法将删除它们并仅保留字符串。

Now that you have the data in the array you can use them while creating the user:

现在您已经拥有数组中的数据,您可以在创建用户时使用它们:

$userFirstLastName = $this->getFirstLastNames(Socialite::driver($provider)->getName());

$user = User::create([
            'email'         => Socialite::driver($provider)->getName()->getEmail(),
            'first_name'    => $userFirstLastName['first_name'],
            'last_name'     => $userFirstLastName['last_name'],
        ]);

ps1: Make sure you change the migrations for users table (Laravel 5.3 uses only "name" field. If you need to have the "first_name" and "last_name" you should change it. Of course run "php artisan migrate:refresh" to implement the changes. All data will be lost.

PS1:请确保您更改用户表中的迁移(Laravel 5.3用途只有“名称”字段如果您需要有“ FIRST_NAME”和“姓氏”,你应该改变它当然跑。“PHP工匠迁移:刷新”来执行更改。所有数据都将丢失。

ps2: Make sure the first_name, last_nameand passwordfields can be nullable. Otherwise you will get an error.

ps2:确保first_namelast_namepassword字段可以为空。否则你会得到一个错误。

ps3: Inside User model, add first_nameand last_nameand remove namein the $fillable property.

ps3:在 User 模型中,在 $fillable 属性中添加first_namelast_name并删除name

ps4: [Not Playstation 4] The first_nameand last_namevalues can be altered by the user within your web app, if the above procedure used your second name as first_nameor last_name. You can't predict what each user uses as a full name, so you need to make assumptions.

ps4:[不是 Playstation 4] first_namelast_name值可以由用户在您的网络应用程序中更改,如果上述过程使用您的第二个名字作为first_namelast_name。您无法预测每个用户使用的全名,因此您需要做出假设。

Hope this helps!

希望这可以帮助!