0

On my website, users can upvote or downvote posts.

SubmissionVote::where('submission_id', $submission->id)->where('user_id', Auth::user()->id)->delete();

$submissionVote = new SubmissionVote;
$submissionVote->submission_id = $submission->id;
$submissionVote->user_id = Auth::user()->id;
$submissionVote->vote = $vote;

So if a user changes their vote, I delete the old vote (without checking if there was an old vote because it's less queries) before recording the new vote.

However, I've seen that you can attach a "unique" parameter to migrations. Something like this.

$table->unique(["submission_id", "user_id"]);

Would this work? And if so, would it make the delete query redundant? Also, if I did it this way would it return an error if there already exists a record (I don't want that)?

0

1 Answer 1

1
$table->unique(["submission_id", "user_id"]);

This would enforce that 1 user could only ever have 1 vote per submission in the table, no matter what happens. Without this constraint, if there is a bug in the code which somehow allows a user to add another vote for the same submission, that second record would just be added, leaving your data "dirty". Or imagine you are updating the table schema and need to manually modify/migrate a bunch of records, and some submission ids change - if something goes wrong and a bunch of records are duplicated, with no uniqueness constraints, they'd all just get added to the table.

With that constraint in place, those things will result in errors, but the data in your table will be protected - invalid records can never be created. The errors will help you find the problem (eg bug in the code), without messing up your data.

If your schema expects 1 vote/user/submission, it's probably a good idea to add that unique index.

But that doesn't remove the need create or maintain those records. You still need to write the code which adds, updates, deletes etc.

I can't see enough of your table structure to be sure, but maybe Laravel's upsert would be useful for you. "Upsert" is the idea of "update a record, or insert one if it doesn't yet exist".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.