答案:通过Laravel的多对多关系实现关注/粉丝系统,1. 创建followers表记录关注关系,2. 在User模型中定义following和followers关联方法,3. 控制器处理关注与取消逻辑,4. 路由注册对应操作,5. 视图根据状态显示关注按钮,并添加辅助方法判断关注状态,6. 可查询粉丝、关注列表及互相关注情况。

实现一个关注/粉丝系统在社交类应用中非常常见,Laravel 提供了优雅的 Eloquent 模型关系和迁移机制,让这个功能开发变得简单高效。下面是一个完整的 Laravel 关注/粉丝系统实现方案。
1. 创建数据库表结构
我们需要一张中间表来记录用户之间的关注关系。这张表通常命名为 followers 或 follows。
运行以下命令创建迁移文件:
php artisan make:migration create_followers_table编辑生成的迁移文件:
public function up()
{
Schema::create('followers', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('follower_id'); // 关注者 ID
$table->unsignedBigInteger('following_id'); // 被关注者 ID
$table->timestamps();
// 确保不能重复关注
$table->unique(['follower_id', 'following_id']);
// 可选:添加外键约束
$table->foreign('follower_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('following_id')->references('id')->on('users')->onDelete('cascade');
});
}
执行迁移:
php artisan migrate2. 定义 Eloquent 模型关系
在 User.php 模型中定义关注与粉丝的关系:
class User extends Authenticatable
{
// 当前用户关注了哪些人(我关注的人)
public function following()
{
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'following_id');
}
// 哪些用户关注了当前用户(我的粉丝)
public function followers()
{
return $this->belongsToMany(User::class, 'followers', 'following_id', 'follower_id');
}
}
这种设计使用了 belongsToMany 自关联,通过中间表维护双向关系。
3. 实现关注/取消关注逻辑
在控制器中添加关注和取消关注的方法:
use Illuminate\Http\Request;
use App\Models\User;
class FollowController extends Controller
{
// 关注用户
public function follow(User $user)
{
$follower = auth()->user();
if ($follower->id === $user->id) {
return back()->with('error', '不能关注自己。');
}
$follower->following()->attach($user->id);
return back()->with('success', '已成功关注该用户。');
}
// 取消关注
public function unfollow(User $user)
{
$follower = auth()->user();
$follower->following()->detach($user->id);
return back()->with('success', '已取消关注。');
}
}
4. 添加路由
在 routes/web.php 中注册路由:
Route::middleware(['auth'])->group(function () {
Route::post('/follow/{user}', [FollowController::class, 'follow'])->name('follow');
Route::delete('/unfollow/{user}', [FollowController::class, 'unfollow'])->name('unfollow');
});
5. 视图中添加关注按钮
在用户详情页或列表页中,根据当前登录用户是否已关注目标用户,显示不同按钮:
@if(auth()->user()->isFollowing($targetUser->id))
@else
@endif
为了方便判断,可以在 User 模型中添加辅助方法:
public function isFollowing($userId)
{
return $this->following()->where('following_id', $userId)->exists();
}
6. 查询示例
获取当前用户的粉丝列表:
$user = auth()->user(); $followers = $user->followers; // 所有粉丝
获取当前用户正在关注的人:
$following = $user->following;
检查是否互相关注(互粉):
// 是否互相关注 $mutual = $user->following->contains($otherUserId) && $otherUser->following->contains($user->id);基本上就这些。整个系统简洁清晰,利用 Laravel 的多对多关系即可完成核心功能。










