user(); $changes = $user->favoriteProducts()->toggle($product); // If changes has any item, that means a product has been attached. $isFavorite = count($changes['attached']) > 0; return response()->json([ 'message' => $isFavorite ? 'Product added to favorites' : 'Product removed from favorites', 'isFavorite' => $isFavorite, ]); } }