如何在laravel中创建Api以关注和取消关注用户
public function follow(){
$id = Auth::id();
$result = User::where('id', '!=', $id)->get();
//return $result;
return response()->json(['data' => $result], 200,[],JSON_NUMERIC_CHECK);
}
public function followUser(user $user){
if (!Auth::user()->isFollowing($user_id)){
Auth::user()->follows()->create([
'target_id' =>$user_id,
]);
return response()->json(['sucess'=>'sucessfully followed']);
}else{
return response()->json(['oops'=>'u already followed ']);
}
}
public function unfollowUser(User $user)
{
if (Auth::user()->isFollowing($user->id)) {
$follow = Auth::user()->follows()->where('target_id', $user->id)->first();
$follow->delete();
return response()->json(['success', 'You are no longer friends with '. $user->name]);
} else {
return response()->json(['error', 'You are not following this person']);
}
}
这是我的代码,这是我在邮递员中使用的路线
Route::post('/followUser/{user}','Api\FollowuserController@followUser');
Route::get('/unfollowUser/{user}','Api\FollowuserController@unfollowUser');
我正在使用遵循用户ID上的sessionid的路由,但一无所获... 我应该怎么做
答案 0 :(得分:1)
我建议您乘坐路线
Route::post('users/{id}/action', 'API\UserController@action');
并针对身体要求:
{
"act":"follow" //or unfollow
}
表:
public function up()
{
Schema::create('action_logs', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('object_id')->unsigned();
$table->enum('object_type',['USER','PAGE','POST']);
$table->enum('act',['FOLLOW','UNFOLLOW','VISIT' ,'LIKE','DISLIKE']);
$table->timestamp('created_at');
$table->foreign('user_id')->references('id')->on('users')
->onDelete('restrict')
->onUpdate('restrict');
});
//Or to make it easier
Schema::create('follower_following', function (Blueprint $table) {
$table->integer('follower_id')->unsigned();
$table->integer('following_id')->unsigned();
$table->primary(array('follower_id', 'following_id'));
$table->foreign('follower_id')->references('id')->on('users')
->onDelete('restrict')
->onUpdate('restrict');
$table->foreign('following_id')->references('id')->on('users')
->onDelete('restrict')
->onUpdate('restrict');
});
在模型(user.php)中
public function followers()
{
return $this->belongsToMany('App\User', 'follower_following', 'following_id', 'follower_id')
->select('id', 'username', 'name','uid');
}
public function following()
{
return $this->belongsToMany('App\User', 'follower_following', 'follower_id', 'following_id')
->select('id', 'username', 'name','uid');
}
操作方法:(如果您有页面和其他对象……最好将此方法用于特征)
public function action($id, Request $request)
{
// $user
switch ($request->get('act')) {
case "follow":
$user->following()->attach($id);
//response {"status":true}
break;
case "unfollow":
$user->following()->detach($id);
//response {"status":true}
break;
default:
//response {"status":false, "error" : ['wrong act']}
}
}