3

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

1
  • Laravel doesn't provide a way to do that - prepare your data as string or use multiple calls using Eloquent (attribute casting as defined on the model) Commented Oct 3, 2017 at 13:12

1 Answer 1

2

Wrap the casted field/data into json_encode:

$insert = [
    0 => [
        'name' => 'name_value',
        'data' => json_encode([
            "key" => "value",
            "key2" => "value2"
           ])
    ]
   1 => [
        'name' => 'name_value2',
        'data' => json_encode([
              'key' => 'value',
              'key2' => 'value2'
            ])
    ]
]

then insert:

Model::insert($insert);

This will NOT create a JSON STRING but will preserve the structure as long as you have this in the Model:

protected $casts = [
   'data' => 'array',
];
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.