I have a three tables post(Model: Post), user(Model: User) and post_user_pivot for votes.
The Schema of my pivot table
Schema::create('post_user', function (Blueprint $table) {
$table->id();
$table->enum('type', ['up', 'down'])->default('up');
$table->unsignedBigInteger('post_id');
$table->unsignedBigInteger('user_id');
$table->timestamps();
});
Storing the votes using attach along with the type, up or down.
Fetching the voters like following ways
$post->voters as $voter using foreach()
Each $voter consist of $user as usual.
But what I want to see the current authenticated user is voted or not, and if voted the type of it(up or down) from voters as mentioned above. No iteration just query for that?
Thanks!
I have tried this
$post->voters->find(auth()->user()->id)->wherePivot('type', '=', 'down');
3
Answers
If you want to see whether the current user has voted or not then you can do something as follows:
First you can improve your migration by replacing unsignedBigInteger with foreignId like so:
If you need to access the count of up and down votes frequently, it may help to add another index for post_id and vote.
in User model:
in Post model:
Create a fluent model for updating user’s vote on a post (add to Post model):
I used syncWithoutDetaching to prevent deleting any existing vote, we just want to update the vote.
then update user’s vote in a single line like so:
in order to check if a user has voted for a post or not you need to define the reverse relation on the user model:
than in your controller you can do something like this:
and in view: