数据已经拿到后,现在要做的就是将用户信息,存入数据库,先去新建一个migration
,增加几个做第三方登录
要用到的字段。
php artisan make:migration add_socialites_to_users_table --table=users
class AddSocialitesToUsersTable extends Migration
{
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('provider')->nullable();
$table->string('uid')->nullable();
$table->string('avatar')->nullable();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('provider');
$table->dropColumn('uid');
$table->dropColumn('avatar');
});
}
}
字段 | 意义 |
---|---|
provider | 区分当前使用的登录服务,例如 QQ 登录,那就存成qq 。如果是微博登录,那就存weibo
|
uid | 保存第三方登录提供的唯一识别 id |
avatar | 第三方登录提供的用户头像 |
确认没问题后,运行下migrate
php artisan migrate
控制器中,现在就要来修改一下callback
部分的方法了。先用provider
和qq
去查询一下,有没有这个用户的信息,如果没有那就将用户信息插入到数据库中。
其中邮箱
和密码
部分,我们直接生成一个假的给用户就好,这里如果不填写,数据库会报错的。
邮箱
的生成规则是provider
的名字和一个加号
这里是qq登录
所以是qq+
,再加上 qq 登录提供的唯一id
,最后拼接上example.com
。
密码
就是随机
生成了一个10位数
的密码。
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Socialite;
use App\User;
use Illuminate\Support\Str;
use Auth;
class SocialitesController extends Controller
{
public function qq()
{
return Socialite::with('qq')->redirect();
}
public function callback()
{
$info = Socialite::driver('qq')->user();
$user = User::where('provider', 'qq')->where('uid', $info->id)->first();
if (!$user) {
$user = User::create([
'provider' => 'qq',
'uid' => $info->id,
'email' => 'qq+' . $info->id . '@example.com',
'password' => bcrypt(Str::random(10)),
'name' => $info->nickname,
'avatar' => $info->avatar,
]);
}
//Auth::login($user);
Auth::login($user, true);
return redirect('/');
}
}
模型部分,找到app/user.php
,增加相关字段的白名单。
protected $fillable = [
'name', 'email', 'password', 'provider', 'uid', 'avatar'
];
已添加到喜欢了