'Adding incoming categories in json with laravel attach() method

Json file...

{'code': '200',
 'msg': '',
 'result': [{'_cdate': '',
              '_date': '2022-05-07 17:45:26.00',
              '_key': '9146247893236409738',
              '_key_cts_brand': 'brand',
              '_key_cts_title': 'product title',
              '_key_cts_price': '100',
    'm_categories': [
        {'_cdate': '2021-11-29 10:40:02.00',
          '_date': '2022-05-07 17:45:26.00',
          '_key': '9079201',
          'key_cts_item_category_1': '8972814',
          'key_cts_item_category_2': '9079130',
          'key_cts_item_category_3': '9079171',
          'key_cts_item_category_4': '8976016',
          'key_cts_item_category_5': '0',
          'key_cts_item_category_6': '0',
          'key_cts_stock': '9146247893236409738',
          '_key_top_1': '',
          '_key_top_2': '8972814',
          '_key_top_3': '9079130',
          '_key_top_4': '',
          '_key_top_5': '',
          '_key_top_6': '',
        }
    ]

I have 6 categories coming from json. Categories come with key_cts_item_category tag. I'm trying to print them to my database them with attach() on the Laravel side.

$product = new Product();
$product->brand_id =  $result['_key_cts_brand'];
$product->title =  $result['_key_cts_title'];
$product->price =  $result['_key_cts_price'];
$product->save();

foreach($result['m_categories'] as $cats){
    Category::find($cats['key_cts_item_category_1']);
    $product->categories()->detach();
    $product->categories()->attach(array($cats['key_cts_item_category_1'],$cats['key_cts_item_category_2'],$cats['key_cts_item_category_3'],$cats['key_cts_item_category_4'],$cats['key_cts_item_category_5'],$cats['key_cts_item_category_6']));
}

I did something like above, but it doesn't work properly. How can I check the incoming categories and add them all?

database :: There are indexes and foreign_key in the database.

product_categories
product_id  -  category_id
9079201         8972814
9079201         9079130
9079201         9079171
9079201         8976016

I'm trying to get an image like this



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source