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

deansatch's avatar

Getting pivot id on attach()

I am fairly new to laravel and I'm trying to build an 'add to basket' script. It consists of 3 tables.

  • basket - id, session_id
  • basket_product - id, basket_id, product_id
  • basket_options - id, basket_id, product_id, basket_product_id, opt_val, opt_name

Basically I am trying to insert to all 3 tables when adding a product to basket:

  • Firstly it inserts the current session id to 'basket'
  • Then inserts the product_id & basket_id to basket_product
  • Then inserts the options & IDs to basket_options where basket_product_id = basket_products.id

The reason for the basket_products having an id and using it in the basket_options table is because the same product_id may be in there several times if someone wants to buy the same item but with different options attached

I have tried using basket_product as a pivot table and doing

$Basket = Basket::find($basket_id); 
$Basket->options()->attach($input['product_id']);

But to then run the next part (inserting options) I need to have the id of the pivot table

My question is a) how would I get that ID b) is there a better way of doing this all round?

0 likes
3 replies
xkts's avatar

Hello @deansatch

As an alternative, maybe it is not necessary to retrieve the id. You could wait for the user to select the options (name and value) and then run:

$Basket = Basket::find($basket_id);
$Basket->options()->attach([
            $input['product_id'] => [
                'opt_val' => 'value_of_option',
                'opt_name' => 'name_of_option'
            ]
        ]);
Snapey's avatar

you could make a BasketOptions model and insert into it rather than attaching?

Please or to participate in this conversation.