我在玩Laravel身份验证。
在使用Composer刚创建的Laravel应用上,我按照说明进行操作,直到这一点为止(已包括)
https://laravel.com/docs/5.8/api-authentication#generating-tokens
但是,当我注册新用户时,api_token字段为NULL。
为了在用户注册时开始生成api令牌,我还需要做什么?
在RegisterController中创建方法:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'api_token' => Str::random(60),
]);
}
Run Code Online (Sandbox Code Playgroud)
迁移(我称其为令牌)更新用户表:
class Token extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('api_token', 80)->after('password')
->unique()
->nullable()
->default(null);
});
}
Run Code Online (Sandbox Code Playgroud)
应用\用户模型:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Run Code Online (Sandbox Code Playgroud)
在您的用户模型中,将“ api_token”添加到您的可填充内容中
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'api_token'
];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
443 次 |
| 最近记录: |