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 } }
The efficient way to check if the record exists you must use is_null method to check against the query. The code below might be helpful: $user = User::where('email', '=', Input::get('email')); if(is_null($user)){ //user does not exist... }else{ //user exists... }
First, we check if the record exists with the EXISTS keyword. EXISTS executes the query we tell it to (the SELECT ) and returns a boolean value. If it finds the record, we return 'This record already exists!' to our recordset and do nothing else.
You can call eloquent count function to get count and then check if count is equal to zero. if($collection->isEmpty()){ //products table is empty. }
You may want something like this:
$user_favorites = DB::table('user_favorites') ->where('user_id', '=', Auth::user()->id) ->where('item_id', '=', $item->id) ->first(); if (is_null($user_favorites)) { // It does not exist - add to favorites button will show } else { // It exists - remove from favorites button will show }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With