Search code examples
phplaraveleloquentlogiclaravel-blade

increment doesn't apply at the first time


i'm newbie in laravel and i'm working on a shop website and i've got stuck in the cart part of the project. and for that i'm using a pivot table with ManyToMeny relation tables

the main problem is when i add to the cart for the first time it gives me always one, but in the second time it increments the third time it increments too. i searched in the pivote table structure and i found 1 as a default value.

first add

first add

result of the first add

results of the first add

second add second add

results of the second add it increments !

results of the second add

i don't know how to change the value of the given 1 in the first. I don't know what to change to make the first add value like the input value. default value

i think the expected outcome of this code is to increment the value of 0 with the value given by input number

this is my controller

$found = false;
$user = Auth::user();
$product = produit::find($id);
if (!$product || !$user) {
    abort(404);
}
if($product->rupture_stock == true){
    return redirect()->back()->with('error', 'Rupture de stock');
}
$panier = $user->panier;    


foreach ($panier->produits as $pr) {
    if ($pr->id == $id){
        $found = true;
        $qt = $pr->pivot->quantite;
        $first_num = $request->get('quantite');
        // $first_num = $_POST['quantite'];
        $second_num = 0;
        $result = '';
        // $qt = $_POST['quantite'];
        if (is_numeric($first_num) && is_numeric($second_num)) {
            $result = $first_num + $second_num;
            $qt += $result;
        }
        $panier->produits()->updateExistingPivot($pr->id, ['quantite' => $qt]);
    }
}
if (!$found) {
    $panier->produits()->attach($product->id);
}

this is my blade

<form action="{{ url('add/'.$prod->id) }}" method="post" style="margin-bottom:20px" class="cart"  id="product_addtocart_form" enctype='multipart/form-data'>
@csrf
    <input type="number" value="" name="quantite"  class="text" step="1" min="1" max="11" size="4" placeholder="" inputmode="numeric" />
<button style="border-radius: 50px; /*padding:0 20px; margin-left:40px*/" type="submit" name="add-to-cart" value="352" class="single_add_to_cart_button button alt">Ajouter</button>
</form>


Solution

  • You can do it more simple by using syncWithoutDetaching:

    $user = Auth::user();
    $product = produit::find($id);
    if (!$product || !$user) {
        abort(404);
    }
    if($product->rupture_stock == true){
        return redirect()->back()->with('error', 'Rupture de stock');
    }
    $panier = $user->panier;    
    
    $panier->produits()->syncWithoutDetaching([$id => ['quantite' => (int)request('quantite')]]);
    

    https://laravel.com/docs/8.x/eloquent-relationships#syncing-associations