I'm trying to build voting system for my web page (Laravel 5). Now, any user can vote multiple times, I want to fix it.
Here is my code in php:
public function addVote()
{
$bikepoint = $this->bikepoint->find($id);
$userid = \Sentry::getUser()->id;
$votesid = \DB::table('bikepoints')->select('votesuid')->where('votesuid', 'LIKE' , $userid)->get();
if (...) {
$bikepoint->votes = $bikepoint->votes + 1;
$bikepoint->votesuid = $bikepoint->votesuid . $userid . '; ';
echo 'Success!';
}
else {
echo 'Fail!';
}
$bikepoint->save();
}
My DB table:
id title votes votesuid
1 point1 2 93; 22;
2 point2 3 92; 28; 47;
3 point3 45 ...
4 point4 32 ...
5 point5 12 ...
So when user click the "Add vote" button, a function adds its ID to the votesuid
field and one vote to the votes
field.
I want to check if the user has already voted by checking if his ID is placed in the votesuid
field. And, if so, the user cannot vote anymore.
For example, users with IDs 92
, 28
and 47
should not be able to vote another time.
As suggested by others in the comments, yes, you do need to change your system so that each vote has it's own record on a table.
So create a Votes table and a Laravel model class for it, and give your Users model class a hasMany()
relationship to Votes.
That's actually not too much work, is it?
But now then the solution to your question becomes trivially easy -- ie:
$votes = Sentry::getUser()->votes;
As things stand, you would need to do sub-string LIKE
queries, which are much harder to write, and will also give you major performance problems when your DB starts getting bigger, so yes, you definitely need to be refactoring it now.