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?