Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Lara_Love's avatar

how can get id in this session ?

ERROR: Undefined array key "id" in form

@ php

$total = 0

@ endphp

                @ if(session('cart'))

                    @ foreach(session('cart') as $id => $details)

                        @ php $total += $details['price'] * $details['quantity'] @endphp
                        
							 <input type="hidden" name="product_id" value="{{ $id }}" >
                             
                                    {{ $id }}
                               

                                <input type="hidden" name="name" value="{{ $details['name'] }}">
                                   {{ $details['name'] }}
                                
                                    <input type="hidden" name="quantity" value="{{ $details['quantity'] }}">
                                    {{ $details['quantity'] }}
                                
                                    <input type="hidden" name="price" value="{{ $details['price'] }}">
                                    {{ $details['price'] }}
                               
                    @endforeach

in controller

public function ad(Request $request)

{

    $product = $request->session()->get('cart');

// dd($product);

    Faktor::create([

        'user_id' => 1,

        'product_id' =>  $product['product_id'],-->ERROR: Undefined array key "id"

        'total' => 1,

    ]);

    return redirect()->back();

dd($product);

^ array:2 [▼

1 => array:5 [▼

"product_id" => 1

"name" => "ssd samsumg "

"quantity" => 1

"price" => "1000"

"image" => "20221014072724.jpg"
0 likes
4 replies
Nakov's avatar
Nakov
Best Answer
Level 73

So you see there is no id in your array.. you should get the product_id instead

'product_id' =>  $product['product_id'],
1 like
Lara_Love's avatar

@Nakov

Hello,

the problem is that whatever I write gives this error.

Undefined array key "product_id" or Undefined array key "id"

again and again

Nakov's avatar

@LoverCode ah, I see now the results.. you have array of arrays which is normal, if you add multiple products to the cart.. make sure you name things correctly..

$products = $request->session()->get('cart');

foreach ($products as $product)
{
		Faktor::create([

		    'user_id' => 1,
            'product_id' =>  $product['product_id'],
            'total' => 1,

    ]);
}
    

    return redirect()->back();
1 like
Lara_Love's avatar

hi dear friend

  • After a long time, I just started training. Yes, I want to save all the products that come from the form, but I don't know what is code in controller.
1 like

Please or to participate in this conversation.