phpmysqleloquentmass-assignmentlaravel-5.6

How to prepare PHP multidimensional arrays for Laravel Mass updateOrCreate()?


I am trying to mass insert into Laravel (5.6) Model. Having issues with array preparations; It returns

lluminate \ Database \ QueryException (42S22)
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' 
(SQL: insert into `_geolocation` (`0`, `1`, `2`, `3`, `4`) values 
(Manchester,+UK, Manchester,+UK, Manchester,+UK, Manchester,+UK, 
Manchester,+UK))

I am generating arrays like this:

if($outputTo->status->message == "OK"){ // if
    for ($i = 0; $i < $outputTo->total_results; $i++) {
        //print_r($outputFrom->results[$i]->geometry->lat);
        $geodata_b [] =[
            $formattedAddrTo,
            $outputTo->results[$i]->formatted,
            $outputTo->results[$i]->geometry->lat,
            $outputTo->results[$i]->geometry->lng,
            ];
    }
}

This are my array`s output;

    array:5 [▼
  0 => array:4 [▼
    0 => "Manchester,+UK"
    1 => "Manchester, Greater Manchester, England, United Kingdom"
    2 => 53.4791301
    3 => -2.2441009
  ]
  1 => array:4 [▼
    0 => "Manchester,+UK"
    1 => "Chapel Street Primary School, Chapel Street, Manchester M19 3GH, United Kingdom"
    2 => 53.443957
    3 => -2.1858478
  ]
  2 => array:4 [▼
    0 => "Manchester,+UK"
    1 => "The Manchester, Lytham Road, Bispham FY1 6AH, United Kingdom"
    2 => 53.8067298
    3 => -3.0549142
  ]
  3 => array:4 [▼
    0 => "Manchester,+UK"
    1 => "The Manchester, Bromsgrove Road, Bromsgrove B62 0HH, United Kingdom"
    2 => 52.4003403
    3 => -2.0539726
  ]
  4 => array:4 [▼
    0 => "Manchester,+UK"
    1 => "The Harlequin, Spitalfields, Sheffield S3 8GG, United Kingdom"
    2 => 53.3884864
    3 => -1.4663405
  ]
]

Inserting code;

    $geolCache = \App\Geolocation::updateOrCreate([$geodata_b]);

My Model;

protected $fillable = ['adrr','faddr','lat','lng'];

Please could anybody help me how to fix this issue?


Solution

  • You are not following key-value pairs. Try this code

    if($outputTo->status->message == "OK"){ // if
        for ($i = 0; $i < $outputTo->total_results; $i++) {
            $geodata_b [] = [
                'adrr' => $formattedAddrTo,
                'faddr' => $outputTo->results[$i]->formatted,
                'lat' => $outputTo->results[$i]->geometry->lat,
                'lng' => $outputTo->results[$i]->geometry->lng,
                ];
        }
    }