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 permalink pages, I have an 'Add to favorites' button which inserts a new row into user_favorites
I want to be able to replace it for a 'Remove from favorites' button if the user already has it in their favorites.
I can't figure out the logic behind this - do I need to check if a row exists in user_favorites
that has the current user's id and the permalink item id? This did not work for me:
if (Auth::user()->id) {
if (!is_null(DB::table('user_favorites')->where('user_id', '=', Auth::user()->id)->where('item_id', '=', $item->id)->first())) {
// remove from favorites button will show
}
}
You may want something like this:
I advise you to use
exists()
orcount()
to check, not usefirst()
.The fastest way:
Or:
SQL:
The faster way: only select id
SQL:
The normal way:
SQL:
The simplest way to do is to use
toggle()
method of many-to-many relationship.e.g.
It also returns an array which tells you if the
ID
is attached or detached in DB.Let
User_favorite
be a model that accesses youruser_favorites
table