I have a data structure that has the following columns:
id => increments()
name => string()
data => string()
In my model, I cast the data column to an array.
protected $casts = [
'data' => 'array'
];
In a for loop I create a multidimensional array like this called $data and I assign it to the 'data key of my $temp array and I push it in an array called $finals.
$temp = [
'name' => $variable1,
'data' => $data
]
array_push($finals, $temp)
Unfortunately, Laravel's bulk insert does not allow me to execute a bulk insert when I have a multidimensional array where one of the values is an array. In order to insert this type of multidimensional array I have to create the following foreach loop (which I don't like)
foreach($finals, $final)
{
ModalName::create($final);
}
Is there a way that I could insert such a data structure in a single statement and not loop through each element of the array. Something like
ModelName::create($finals);
Note that, I've tried to replace the value of the 'data' key with a hardcoded static value in place of the array and the rows are inserted correctly.
The multidimensional array $finals looks like this.
array:2 [
0 => [
'name' => 'name_value',
'data' => [
"key" => "value",
"key2" => "value2"
]
]
1 => [
'name' => 'name_value2',
'data' => [
'key' => 'value',
'key2' => 'value2'
]
]
]
EDIT::
Please note that when I try to use
ModelName::create($finals) or
ModalName::insert($finals) or
DB::table('table_name')->insert($finals)
I get the following query exception: Array to string conversion
dataas string or use multiple calls usingEloquent(attribute casting as defined on the model)