Skip to content
Advertisement

Laravel 7 Select a record if the id dosen’t exist in another table

Using laravel 7 i am trying to select an item record as long as that records id dosen’t appear in another table but only as long as the id in the other table is accompanied by the users id

Item table
id
item name


Banned Items
ItemID
UserID

Edit 1 If an item is banned it its added to the banned items table that stores the item id and the user id when i load the items i need to exclude the items that appear in the banned items table but only for the user that is banned for

Items table
1 Apple
2 Pear

Banned Items
1 1
1 2

Users
1 username1 password1
2 username2 password2

so if the item is banned for that user don’t select the item. I’m struggling to do this. Thanks

Advertisement

Answer

I didn’t understand how did you create a relation between banned items and users, but you need that relation. So I assume the columns on banned_items table are

id, user_id, item_id
$bannedItems = BannedItem::where('user_id', Auth::id())->get()->pluck('id');
// If you don't have a model for pivot table:
$bannedItems = DB::table('banned_items')->where('user_id', Auth::id())->get()->pluck('id');
$items = Item::whereNotIn('id', $bannedItems)->get();

should return the items that weren’t banned by the current user.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement