Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

joedawson's avatar

firstOrCreate - check if created or if first?

Hello,

My scenario is I have three models. User, Track & Vote.

The idea is that a user can "vote" a track. So there are obviously some relations. What I want to do, is if a user "votes" for the track, insert a new vote into my table. I currently have this working like so.

$track->votes()->firstOrCreate(['user_id' => $user->id]);

What I want to do, is if the record already exists - meaning the user has already voted for the track - delete the vote. Otherwise create one.

I hope this makes sense, any ideas how I can achieve this?

I also don't belive I'm at liberty to use a pivot table as there are three models.

Thanks

0 likes
5 replies
jekinney's avatar
jekinney
Best Answer
Level 47

You can still associate the relationship as a pivot and use the toggle() method.

Likes being used by a model might be redundant, but either way has no bearing on a belongsToMany() relationship. You can in theory have infinite amount of relationships between two models.

joedawson's avatar

Thanks @jekinney, just found Jeff's tutorial on the new toggle method. Haven't even watch any 5.3 videos since it's release, too busy lol.

I've just implemented it, how would I check if the user has "voted" the track in my case?

Snapey's avatar

This should toggle the entry

$vote=$track->votes()->firstOrCreate(['user_id' => $user->id]);

if(!$vote->wasRecentlyCreated){
    $vote->delete();
}

Find previous vote, and if it existed then delete it, else create it.

1 like
martinbean's avatar

I also don't belive I'm at liberty to use a pivot table as there are three models.

@JoeDawson Surely a “vote” is just a relationship between a User and a Track?

joedawson's avatar

@martinbean yeah, I did have a Vote model previously. So I could query them for stats later, but I don't really have any intention to right now.

I've just set up a votes table with user_id and track_id columns and created a votes() method using a belongsToMany between the relations, it's working perfectly now. Sorry :D

Please or to participate in this conversation.