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

实现一个关注/粉丝系统在社交类应用中非常常见,Laravel 提供了优雅的 Eloquent 模型关系和迁移机制,让这个功能开发变得简单高效。下面是一个完整的 Laravel 关注/粉丝系统实现方案。
我们需要一张中间表来记录用户之间的关注关系。这张表通常命名为 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 migrate在 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 自关联,通过中间表维护双向关系。
在控制器中添加关注和取消关注的方法:
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', '已取消关注。');
    }
}
在 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');
});
在用户详情页或列表页中,根据当前登录用户是否已关注目标用户,显示不同按钮:
@if(auth()->user()->isFollowing($targetUser->id))
    <form action="{{ route('unfollow', $targetUser) }}" method="POST">
        @csrf
        @method('DELETE')
        <button type="submit">取消关注</button>
    </form>
@else
    <form action="{{ route('follow', $targetUser) }}" method="POST">
        @csrf
        <button type="submit">关注</button>
    </form>
@endif
为了方便判断,可以在 User 模型中添加辅助方法:
public function isFollowing($userId)
{
    return $this->following()->where('following_id', $userId)->exists();
}
获取当前用户的粉丝列表:
$user = auth()->user(); $followers = $user->followers; // 所有粉丝
获取当前用户正在关注的人:
$following = $user->following;
检查是否互相关注(互粉):
// 是否互相关注 $mutual = $user->following->contains($otherUserId) && $otherUser->following->contains($user->id);
以上就是laravel如何实现一个关注/粉丝系统_Laravel关注与粉丝系统实现教程的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号