config/auth.php
'api' => [ 'driver' => 'token', 'provider' => 'users', 'hash' => true, ],
php artisn make:migration add_api_token_to_users --table=users
\database\migrations\2021_07_20_210539_add_api_token_to_users.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddApiTokenToUsers extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { // $table->string('api_token',64)->unique(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { // $this->dropColum(['api_token']); }); } }View Code
php artisan migrate
php artisan tinker
str_random(60)
把生成的token添加到字段里
protected function create(array $data) { $user = User::create([ 'name' => $data['name'], 'email' => $data['email'], 'avatar' => '/image/avatars/default.jpg', //这里其实不需要再设置activation_token的值,也不需要再在验证后设置activated=1 采用Laravel提供的新功能验证用户邮箱即可 默认带一个email_verified_at字段,且更加完善具有过期时间戳和签名 'activation_token' => str_random(40),//通过composer require laravel/helpers安装扩展包 'password' => Hash::make($data['password']), //添加token 'api_token'=>str_random(60) ]); $this->sendVerifyEmailTo($user); return $user; }
protected $fillable = [ 'name', 'email', 'password', 'avatar','activation_token','api_token' ];
let api_token = document.head.querySelector('meta[name="api-token"]'); if (api_token) { window.axios.defaults.headers.common['Authorization'] = api_token.content; } else { console.error('Authorization token not found'); }
2.2.2