0 设置
config/auth.php
'api' => [ 'driver' => 'token', 'provider' => 'users', 'hash' => true, ],
1 添加users表字段api_token
php artisn make:migration add_api_token_to_users --table=users
databasemigrations2021_07_20_210539_add_api_token_to_users.php
<?php use IlluminateSupportFacadesSchema; use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; 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']); }); } }
php artisan migrate
php artisan tinker
str_random(60)

把生成的token添加到字段里
2 修改代码
2.1 注册相关代码
2.1.1 appHttpControllersAuthRegisterController.php
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; }
2.1.2 appUser.php
protected $fillable = [ 'name', 'email', 'password', 'avatar','activation_token','api_token' ];
2.2 接口代码
2.2.1 esourcesjsootstrap.js
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 esourcesviewslayoutsapp.blade.php
<meta name="api-token" content="{{ Auth::check() ? 'Bearer '.Auth::user()->api_token:'Bearer '}}">
2.2.3 outesapi.php
Route::middleware('auth:api')->post('/question/follower',function (Request $request){
//request('question') 或者这样获取
/*$followed = !! AppFollow::where('question_id',$request->get('question'))
->where('user_id',$request->get('user'))
->count();*/
$user = Auth::guard('api')->user();
$followed = $user->followed($request->get('question'));
return response()->json(['followed'=>$followed]);
});
Route::post('/question/follow',function (Request $request){
/*
$followed = AppFollow::where('question_id',$request->get('question'))
->where('user_id',$request->get('user'))
->first();
if ($followed !== null){
$rs = $followed->delete();
$question->decrement('followers_count');
if ($rs){
return response()->json(['followed'=>false]);
}else{
return response()->json(['error'=>'请稍后再试']);
}
}
$attributes = [
'question_id'=> $request->get('question'),
'user_id' => $request->get('user')
];
AppFollow::create($attributes);*/
$user = Auth::guard('api')->user();
$question = AppQuestion::find($request->get('question'));
$followed = $user->followThis($question->id);
if (count($followed['detached'])>0){
$question->decrement('followers_count');
return response()->json(['followed'=>false]);
}
$question->increment('followers_count');
return response()->json(['followed'=>true]);
})->middleware('auth:api');
2.3 组件代码
esourcesjscomponentsQuestionFollowButton.vue
<template>
<button class="btn "
v-text="text"
v-on:click="follow"
v-bind:class="{'btn-success':followed,'btn-info':!followed}">
</button>
</template>
<script>
export default {
name: "QuestionFollowButton",
props:['question','user'],
mounted(){
axios.post('/api/question/follower',{'question':this.question,'user':this.user}).then(res => {
this.followed = res.data.followed;
console.log(res.data)
},error => {
//console.log(error);
//console.log(error.response.status)
if(error.response.status==401){
this.auth = false
}
})
},
data(){
return {
followed:false ,
auth:true
}
},
computed:{
text(){
if (!this.auth){
return '登录后关注'
}
return this.followed ? '已关注':'关注该问题'
}
},
methods:{
follow(){
//alert('Hello')
axios.post('/api/question/follow',{'question':this.question,'user':this.user}).then(res => {
this.followed = res.data.followed;
console.log(res.data)
})
}
}
}
</script>
<style scoped>
</style>