Search code examples
phplaravelvote

laravel user only vote once in a form


I have a question about an user vote system that I want to make.

Is it possible to make kind of role model in the users model, and that if the user has voted (it is a form that they fill in) they cannot view that page or cannot submit the form again because they already voted once.

But I am not sure if this is possible, do you know if there is a way to make this possible?

Update

Users Model:

protected $table = 'users';

protected $fillable = ['email', 'password', 'voted'];

protected $hidden = ['password', 'remember_token'];

Option Model:

protected $table = 'options';

protected $fillable = ['id, points'];

User migration

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

Option Migration

public function up()
{
    Schema::create('options', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('option');
        $table->tinyInteger('points');
        $table->timestamps();
    });
}

Maybe good to know, in my RoundOneController@update I have 2 If else statements. (If select box 1 is id from database, then update, else make new one. Same for select box 2) But if there is a possibility that when this has ended the users table will be updated and the voted column will change to 1, than the user cannot vote anymore.


Solution

  • Without seeing how your code is setup, there are in fact several ways to accomplish this.

    One way would be to have a voted column in your User Model. If you set it up as a boolean in your Migrations with a default value of 0,

    Schema::table('users', function ($table) {
        $table->boolean('voted')->default(0);
    });
    

    then you can just set it to '1' after a User votes. Then set up Middleware for the voting page which checks for the presence of this value.

    middleware file:

    public function handle($request, Closure $next)
    {
         if (Auth::user()->voted) {
             return redirect('home');
         }
    
         return $next($request);
    }
    

    Make sure to register the Middleware in kernal.php

    protected $routeMiddleware = [
        ......
        'voted' => \App\Http\Middleware\RedirectIfVoted::class,
    ];
    

    and apply it to your route(s):

    Route::get('user/vote', ['middleware' => ['voted'], function () {
        //
    }]);