micky micky - 3 months ago 9
MySQL Question

avoiding loop while checking the values

I have the watchlist table. user can add product to the watchlist. this way user_id and product_id is populated.

id user_id product_id
1 1 3
2 1 4
3 1 5
4 2 3
5 2 4
.. .. ..


I want to have the button 'Add product to watchlist' if only that product donot already is in this watchlist table of that user.ohterwise 'Remove product from watchlist' button.
this is what i have in controller.

public function index()
{
$products=Product::where(['status'=>'On sale'])->get();
$check=Watchlist::where(['user_id'=>Auth::user()->id])->get();
return View('product.index',['products'=>$products,'check'=>$check]);
}


and in the view:
if i do the following the button appears as many times as there is user_id in watchlist table because of that loop. but i need the loop to check for all product_id of the user.

<?php foreach($products as $product):?>
<?php foreach($check as $che):?>
<?php
if($che->product_id==$product->product_id)
{
?><a href="" class="removewatchlist" data-id="<?php echo $product->product_id;?>"><button class="btn btn-info">Remove from watchlist</button></a> <?php
}
else
{
?><a href="" class="watchlist" data-id="<?php echo $product->product_id;?>"><button class="btn btn-info">Add to watchlist</button></a> <?php
}

?>
<?php endforeach;?>
<?php endforeach;?>

Answer

You could simple create an array with all the product ids which are in the watchlist in the controller, like:

$chraw = Watchlist::where(['user_id'=>Auth::user()->id])->get();
$check = array();
foreach($checkb as $che)
    $check[] = $che->product_id;

And in the view simply check if the id is in the array:

<?php foreach($products as $product): ?>
    <?php if(in_array($product->product_id, $check)): ?>
      ...
Comments