首页 > php框架 > Laravel > 正文

laravel如何实现一个简单的投票系统_Laravel简单投票系统实现方法

裘德小鎮的故事
发布: 2025-10-22 08:39:01
原创
200人浏览过
先创建投票表并定义模型关系,再编写控制器处理投票逻辑,最后设置路由和视图实现文章赞踩功能。

laravel如何实现一个简单的投票系统_laravel简单投票系统实现方法

在Laravel中实现一个简单的投票系统并不复杂。只需要几个步骤:创建数据表、定义模型关系、编写控制器逻辑以及设置路由和视图。下面是一个基础但完整的实现方法,适用于文章或帖子的“赞”或“踩”功能。

1. 创建数据库迁移

假设我们要为文章(Post)实现投票功能,先创建一张投票记录表:

php artisan make:migration create_votes_table
登录后复制

编辑迁移文件:

Schema::create('votes', function (Blueprint $table) {
    $table->id();
    $table->foreignId('post_id')->constrained()->onDelete('cascade');
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
    $table->tinyInteger('type'); // 1 表示赞成,0 表示反对
    $table->timestamps();

    $table->unique(['post_id', 'user_id']); // 每个用户每篇文章只能投一票
});
登录后复制

运行迁移:

php artisan migrate
登录后复制

2. 定义模型关系

Post.php 模型中添加:

public function votes()
{
    return $this->hasMany(Vote::class);
}

public function upVotes()
{
    return $this->votes()->where('type', 1);
}

public function downVotes()
{
    return $this->votes()->where('type', 0);
}
登录后复制

User.php 模型中确保已启用Auth,并可选添加:

public function votes()
{
    return $this->hasMany(Vote::class);
}
登录后复制

创建 Vote.php 模型:

钛投标
钛投标

钛投标 | 全年免费 | 不限字数 | AI标书智写工具

钛投标97
查看详情 钛投标
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Vote extends Model
{
    protected $fillable = ['post_id', 'user_id', 'type'];
}
登录后复制

3. 编写投票控制器

生成控制器:

php artisan make:controller VoteController
登录后复制

VoteController.php 中添加投票逻辑:

use App\Models\Post;
use App\Models\Vote;
use Illuminate\Http\Request;

public function vote(Request $request, Post $post)
{
    $request->validate([
        'type' => 'required|in:1,0',
    ]);

    // 用户对当前文章的已有投票
    $existingVote = $post->votes()->where('user_id', auth()->id())->first();

    if ($existingVote) {
        // 更新已有的投票
        $existingVote->update(['type' => $request->type]);
    } else {
        // 创建新投票
        $post->votes()->create([
            'user_id' => auth()->id(),
            'type' => $request->type,
        ]);
    }

    return back()->with('success', '投票成功!');
}
登录后复制

4. 设置路由

routes/web.php 中添加:

use App\Http\Controllers\VoteController;

Route::middleware(['auth'])->group(function () {
    Route::post('/posts/{post}/vote', [VoteController::class, 'vote'])->name('posts.vote');
});
登录后复制

5. 在视图中添加投票按钮

例如在展示文章的Blade模板中:

<div>
    <p>{{ $post->title }}</p>
    <p>{{ $post->content }}</p>

    <p>
        赞: <strong>{{ $post->upVotes()->count() }}</strong> |
        踩: <strong>{{ $post->downVotes()->count() }}</strong>
    </p>

    <form action="{{ route('posts.vote', $post) }}" method="POST">
        @csrf
        <button type="submit" name="type" value="1" 
                {{ $post->votes()->where('user_id', auth()->id())->where('type', 1)->exists() ? 'disabled' : '' }}>
            赞
        </button>
        <button type="submit" name="type" value="0"
                {{ $post->votes()->where('user_id', auth()->id())->where('type', 0)->exists() ? 'disabled' : '' }}>
            踩
        </button>
    </form>
</div>
登录后复制

这样就能实现每个用户对每篇文章只能投一次赞或踩,且可修改自己的选择。

基本上就这些。你可以根据需要扩展功能,比如AJAX提交、前端实时更新计数等。核心逻辑清晰,易于维护。

以上就是laravel如何实现一个简单的投票系统_Laravel简单投票系统实现方法的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号