【问题标题】:laravel user only vote once in a formlaravel 用户只在表单中投票一次
【发布时间】:2015-11-19 15:08:48
【问题描述】:

我有一个关于我想要制作的用户投票系统的问题。

是否可以在用户模型中创建一种角色模型,并且如果用户已投票(这是他们填写的表单),他们将无法查看该页面或无法再次提交表单,因为他们已经投票过一次.

但我不确定这是否可能,你知道是否有办法使这成为可能吗?

更新

用户模型:

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 中,我有 2 个 If else 语句。 (如果选择框 1 是数据库中的 id,则更新,否则创建新的。选择框 2 相同) 但是如果有可能在结束后用户表将被更新并且投票列将更改为 1,那么用户将无法再投票。

【问题讨论】:

    标签: php laravel vote


    【解决方案1】:

    如果不了解您的代码是如何设置的,实际上有几种方法可以实现这一点。

    一种方法是在您的User 模型中添加一个voted 列。如果您在 Migrations 中将其设置为 boolean,默认值为 0,

    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 () {
        //
    }]);
    

    【讨论】:

    • 啊哈好吧,当用户提交表单时,您使用 if 函数将布尔值更改为 1?
    • @JeroenvanRooijen 您将提交voteForm 到您的控制器方法,然后将值“1”存储为“投票”。即User::update([ 'voted' => 1 ])
    • 它还没有帮助到我。我更新了我的用户迁移率,制作了一个名为 RedirectIfVoted 的中间件,并更新了我的 kernal.php。我还制作了一个 __construct 并将此代码放入其中 $this->middleware('voted'); 但我不知道如何使用 store 方法更改另一个控制器中的布尔值(因为我将那个用于我的表单,并且我没有使用 UserController) .
    • 您的表单使用的是哪个控制器?你们的模型是如何相互关联的?
    • 我的表单正在使用 RoundOneController,我还没有关联我的模型,因为它没有必要。我将更新我的帖子并将模型和迁移放在第一篇文章中
    猜你喜欢
    • 2012-03-15
    • 2019-06-07
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多