PHP code example of free3_5man / laravel-eloquent-batch

1. Go to this page and download the library: Download free3_5man/laravel-eloquent-batch library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

free3_5man / laravel-eloquent-batch example snippets


use App\Models\Player;
use Freeman\LaravelBatch\BatchUtil;

$data = [
    // this is the first item, columns of this item will be used as insert columns
    // if columns of any other items does not equal to this, false will be returned as result 
    // all the columns of each item olumns default;
$ids = BatchUtil::ofModel(new Player)->batchInsert($data);
// if players primay key auto_increment, insert ids array ([1, 2, 3]) will be returned, else empty array ([]) will be returned

$data[1]['is_captain'] = true;
BatchUtil::ofModel(new Player)->batchInsert($data); // return false

$data = [
    [
        'id' => 1,
        'name' => 'kaka',
        'birthday' => '1982-04-22',
    ],
    [
        'id' => 2,
        'name' => 'nesta',
        'birthday' => '1976-03-19',
    ],
    [
        'id' => 3,
        'name' => 'pirlo',
        'birthday' => '1979-05-19',
    ],
];
BatchUtil::ofModel(new Player)->batchUpdate($data);

$data = [
    [
        'name' => 'kaka',
        'birthday' => '1982-04-22',
    ],
    [
        'name' => 'nesta',
        'birthday' => '1976-03-19',
    ],
    [
        'name' => 'pirlo',
        'birthday' => '1979-05-19',
    ],
];
// batchSave will do batch insert here
$players = collect($data)->map(function($item) {
    return new Player($item);
})->batchSave();    // each player has id
dump($players->pluck('id')->toArray()); // [1, 2, 3]

// batchSave will do batch update here, updated_at will be touched automaticly
$players->map(function($player) {
    return $player->fill([
        'name' => $player->name . '-' . $player->id,
    ]);
})->batchSave();
dump($players->pluck('name')->toArray());   // ['kaka-1', 'nesta-2', 'pirlo-3']