Laravel bulk insert optimization I'm currently using a make shift INSERT on DUPLICATE UPDATE function that relies on a DB raw query from eloquent. I'm looking to improve the quality of the code and the speed. Please take a look

function bulkInsertBookTable($data)
{
    $inserts = [];
    foreach ($data as $item) {
        $inserts[] = implode(', ', ['"' . $item['book_id'] . '"', $item['isbn']]);
    }

    $inserts = Collection::make($inserts);

    $inserts-&gt;chunk(500)-&gt;each(function($ch) {
        $insertString = '';
        foreach ($ch as $element) {
            $insertString .= '(' . $element . '), ';
        }

        $insertString = rtrim($insertString, ", ");

        try {
            DB::insert("INSERT INTO book_datas (`book_id`, `isbn`) VALUES $insertString ON DUPLICATE KEY UPDATE `isbn`=VALUES(`isbn`)");
        } catch (\Exception $e) {
            print_r([$e-&gt;getMessage()]);
        }
    });
}


NOTE:

createOrUpdate function is only valid on model level and does not allow mass insert. Doing Model::insert() will allow to have a $data = [] inserted as long as fillable is used however it will reject if there is a duplicate key
implode works


        $insertString = '';
        foreach ($ch as $element) {
            $insertString .= '(' . $element . '), ';
        }

        $insertString = rtrim($insertString, ", ");



You can replace this section of code with just something like 

        $insertString = '(' . implode('), (', $ch-&gt;all()) . ')';


This is shorter with fewer failure points.  And of course, it avoids having to trim off the extra comma at the end.  

Bound parameters

But actually, it would be better to replace it with something like 

        $insertString = implode(', ', array_fill(0, $ch-&gt;count(), '(?, ?)'));


and then pass the values to DB::insert as an array.  I'd write more of the code for this, but I'm not sure exactly how the Laravel Collection objects work.  

Naming

Data is already plural (the singular is datum).  There is no datas.  

I'd prefer $chunk to $ch.