我有一个关于我想要创建的用户投票系统的问题。
是否可以在用户模型中建立某种角色模型,如果用户已经投票(这是他们填写的表格),他们就无法查看该页面,或者因为已经投票过一次而无法再次提交表格。
但我不确定这是否可能,你知道是否有办法让这成为可能吗?
更新
用户型号:
protected $table = 'users';
protected $fillable = ['email', 'password', 'voted'];
protected $hidden = ['password', 'remember_token'];
选项型号:
protected $table = 'options';
protected $fillable = ['id, points'];
用户迁移
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email')->unique();
$table->string('password');
$table->boolean('voted')->default(0);
$table->rememberToken();
$table->timestamps();
});
}
选项迁移
public function up()
{
Schema::create('options', function(Blueprint $table)
{
$table->increments('id');
$table->string('option');
$table->tinyInteger('points');
$table->timestamps();
});
}
也许很高兴知道,在我的RoundOneController@update我有两个If else语句。(如果选择框1是来自数据库的id,则更新,否则创建新id。选择框2也是如此)但是,如果这一切结束后,用户表将被更新,投票列将变为1,那么用户就不能再投票了。
如果不了解代码是如何设置的,实际上有几种方法可以实现这一点。
一种方法是在User
模型中有一个voted
列。如果您在迁移中将其设置为默认值为0的boolean
,
Schema::table('users', function ($table) {
$table->boolean('voted')->default(0);
});
然后您可以在用户投票后将其设置为"1"。然后为投票页面设置Middleware
,以检查该值的存在。
中间件文件:
public function handle($request, Closure $next)
{
if (Auth::user()->voted) {
return redirect('home');
}
return $next($request);
}
确保在kernal.php
中注册中间件
protected $routeMiddleware = [
......
'voted' => 'App'Http'Middleware'RedirectIfVoted::class,
];
并将其应用于您的路线:
Route::get('user/vote', ['middleware' => ['voted'], function () {
//
}]);