先创建投票表并定义模型关系,再编写控制器处理投票逻辑,最后设置路由和视图实现文章赞踩功能。

在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全自动批量代投简历软件,自动浏览招聘网站从海量职位中用AI匹配职位并完成投递的全自动操作,真正实现’一键职达’的便捷体验。
79 查看详情
<?phpnamespace AppModels;use IlluminateDatabaseEloquentModel;class Vote extends Model{ protected $fillable = ['post_id', 'user_id', 'type'];}
3. 编写投票控制器
生成控制器:
php artisan make:controller VoteController
在 VoteController.php 中添加投票逻辑:
use AppModelsPost;use AppModelsVote;use IlluminateHttpRequest;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 AppHttpControllersVoteController;Route::middleware(['auth'])->group(function () { Route::post('/posts/{post}/vote', [VoteController::class, 'vote'])->name('posts.vote');});
5. 在视图中添加投票按钮
例如在展示文章的Blade模板中:
{{ $post->title }}
{{ $post->content }}
赞: {{ $post->upVotes()->count() }} | 踩: {{ $post->downVotes()->count() }}
@csrf
这样就能实现每个用户对每篇文章只能投一次赞或踩,且可修改自己的选择。
基本上就这些。你可以根据需要扩展功能,比如AJAX提交、前端实时更新计数等。核心逻辑清晰,易于维护。
以上就是laravel如何实现一个简单的投票系统_Laravel简单投票系统实现方法的详细内容,更多请关注php中文网其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/266275.html
微信扫一扫
支付宝扫一扫