1

i try the answer to this about bulk insert in laravel Query builder. my query output is

[
 {"name":"Dayle","id":1,"email":"dayle213@gmail.com"},
 {"name":"John","id":2,"email":"john.doe@gmail.com"}
]

but when i try

   DB::table('staff')->insert($data);

i get error Query\Builder::insert() must be of the type array, object given,

when i try

   DB::table('staff')->insert($data->toArray());

i get error Object of class stdClass could not be converted to string.

how can i insert inn bulk ?

SeyT
  • 773
  • 1
  • 10
  • 23
  • 1
    as in the previous Q with the below data it does work [{"name":"Coder 1","id":4096,"email":"email@example.com"},{"name":"Coder 3","id":43,"email":"emqqqqail@example.com"},{"name":"Coder 3","id":33,"email":"ezzzmail@example.com"},{"name":"Coder 4","id":11,"email":"emawil@example.com"}] – SeyT Feb 11 '21 at 10:01

1 Answers1

1

$data is encoded as JSON object, you need to decode it to make an array:

$data = json_decode($x, true); // array
DB::table('staff')->insert($data);
STA
  • 30,729
  • 8
  • 45
  • 59
  • Could you expand this, to explain what this does, rather than just giving the command? – Andrew Feb 11 '21 at 10:19
  • @Andrew this is the output http://sandbox.onlinephpfunctions.com/code/7a7f25d5bdec6d2b6d2bc9421668b5c5a150c7ae – STA Feb 11 '21 at 10:31
  • 1
    Understood. But to be a useful SO answer, we're after explanation and detail. Thanks. – Andrew Feb 11 '21 at 10:33