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

pfigdev's avatar

Constructing an Eloquent Query

I'm trying to construct an Eloquent query to prevent duplicate items in a database. I have a user ID column (foreign id linked to users table) and an item ID to query against. In my controller, I want to run an if statement that checks if the current user ID and Item ID are present, then don't save item, otherwise, proceed and save item to database. I've tried a bunch of different variations so far and none have worked. Currently have this:

$duplicate = Favorite::select('title_id')
                                ->where('user_id', auth()->user()->id)
                                ->where('title_id', $request->title_id)
                                ->get();

if ( $duplicate) {
	dd('This is a duplicate');
}
///  enter into database

I have no issues saving items to the database, but adding a duplicate check either allows duplicate entries or, depending on my query, flags everything as a duplicate. Do I need to do a subquery?

0 likes
4 replies
tykus's avatar

You can use validation:

[
    'title_id' => [Rule::unique('favorites')->where('user_id', auth()->id())],
]

or if you prefer your approach, and because an Object (even empty Collection) is always truthy, use the exists Builder method instead:

$duplicate = Favorite::where('user_id', auth()->user()->id)
    ->where('title_id', $request->title_id)
    ->exists();

if ( $duplicate) {
	dd('This is a duplicate');
}
1 like
pfigdev's avatar

@tykus I like that validation method, thanks. Using ````exists()``` worked as well, but I like leaving the query mess out of the controller.

Sinnbeck's avatar

Why not make a unique index on those columns together? Then you cannot get duplicates

In a migration

$table->unique(['title_id', 'user_id']);
1 like
pfigdev's avatar

@Sinnbeck Should I use this in conjunction with the validation method described by @tykus, or would adding this index be enough?

Please or to participate in this conversation.