0

Hey guys I have to Arrays named $keys and $values Like this

keys
array:2 [▼
0 => "1"
1 => "2"
]

values
array:2 [▼
0 => "US"
1 => "Canada"
]

And I want to insert them to the database with my controller :

        $keys = $request->key;
    $values = $request->value;


    $datas  = new Collection();
    $datas->key_id = $keys;
    $datas->value = $values;
    $datas->product_id = $product_id;
    ProductSearchValuesModel::create($datas);

But this way is not working What is wrong with my code?

3
  • show your form. Why do you have these items as separate keys and values in the request? Commented Aug 13, 2022 at 14:55
  • @Snapey in the form we duplicate inputs so values send like this : name="keys[]" , name="values[]" Commented Aug 13, 2022 at 15:01
  • 1
    Instead name them items[]['key'] and items[]['value'] then you will only have one array in the request and you can loop over it creating the ProductSearchValuesModel(s) Commented Aug 13, 2022 at 15:26

1 Answer 1

2

It's better to change those array to jSon format. Please! check this code.

$datas  = new Collection();
$datas->key_id = json_encode($keys);
$datas->value = json_encode($values);
$datas->product_id = $product_id;
ProductSearchValuesModel::create($datas);

You'll have to use json_decode($array, 1) whenever you want to pull from database and use them. Also please check field length of that table ProductSearchValues to make sure it can hold that data.

Thanks

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.