I have the following db structure:
items:
id, name, user_id
users table:
id, name
user_favorites table:
id, user_id, item_id
On my items perm
I advise you to use exists()
or count()
to check, not use first()
.
The fastest way:
$result = DB::table('user_favorites')
->where('user_id', '=', Auth::user()->id)
->where('item_id', '=', $item->id)
->exists();
Or:
$result = DB::table('user_favorites')
->where('user_id', '=', Auth::user()->id)
->where('item_id', '=', $item->id)
->count();
SQL:
select count(*) as aggregate from `user_favorites` where *** limit 1
The faster way: only select id
$result = DB::table('user_favorites')
->where('user_id', '=', Auth::user()->id)
->where('item_id', '=', $item->id)
->first(['id']);
SQL:
select id from `user_favorites` where *** limit 1
The normal way:
$result = DB::table('user_favorites')
->where('user_id', '=', Auth::user()->id)
->where('item_id', '=', $item->id)
->first();
SQL:
select * from `user_favorites` where *** limit 1