insert batch and update batch in laravel

Overview

Laravel BATCH (BULK)

Insert and update batch (bulk) in laravel

License Latest Stable Version Total Downloads Daily Downloads

Install

composer require mavinoo/laravel-batch

Service Provider

file app.php in array providers :

Mavinoo\Batch\BatchServiceProvider::class,

Aliases

file app.php in array aliases :

'Batch' => Mavinoo\Batch\BatchFacade::class,

Example Update 1

use App\Models\User;

$userInstance = new User;
$value = [
     [
         'id' => 1,
         'status' => 'active',
         'nickname' => 'Mohammad'
     ] ,
     [
         'id' => 5,
         'status' => 'deactive',
         'nickname' => 'Ghanbari'
     ] ,
];
$index = 'id';

Batch::update($userInstance, $value, $index);

Example Update 2

use App\Models\User;

$userInstance = new User;
$value = [
     [
         'id' => 1,
         'status' => 'active'
     ],
     [
         'id' => 5,
         'status' => 'deactive',
         'nickname' => 'Ghanbari'
     ],
     [
         'id' => 10,
         'status' => 'active',
         'date' => Carbon::now()
     ],
     [
         'id' => 11,
         'username' => 'mavinoo'
     ]
];
$index = 'id';

Batch::update($userInstance, $value, $index);

Example Increment / Decrement

use App\Models\User;

$userInstance = new User;
$value = [
     [
         'id' => 1,
         'balance' => ['+', 500] // Add
     ] ,
     [
         'id' => 2,
         'balance' => ['-', 200] // Subtract
     ] ,
     [
         'id' => 3,
         'balance' => ['*', 5] // Multiply
     ] ,
     [
         'id' => 4,
         'balance' => ['/', 2] // Divide
     ] ,
     [
         'id' => 5,
         'balance' => ['%', 2] // Modulo
     ] ,
];
$index = 'id';

Batch::update($userInstance, $value, $index);

Example Insert

use App\Models\User;

$userInstance = new User;
$columns = [
     'firstName',
     'lastName',
     'email',
     'isActive',
     'status',
];
$values = [
     [
         'Mohammad',
         'Ghanbari',
         '[email protected]',
         '1',
         '0',
     ] ,
     [
         'Saeed',
         'Mohammadi',
         '[email protected]',
         '1',
         '0',
     ] ,
     [
         'Avin',
         'Ghanbari',
         '[email protected]',
         '1',
         '0',
     ] ,
];
$batchSize = 500; // insert 500 (default), 100 minimum rows in one query

$result = Batch::insert($userInstance, $columns, $values, $batchSize);
// result : false or array

sample array result:
Array
(
    [totalRows]  => 384
    [totalBatch] => 500
    [totalQuery] => 1
)

Helper batch()

// ex: update

$result = batch()->update($userInstance, $value, $index);


// ex: insert

$result = batch()->insert($userInstance, $columns, $values, $batchSize);

Tests

If you don't have phpunit installed on your project, first run composer require phpunit/phpunit

In the root of your laravel app, run ./vendor/bin/phpunit ./vendor/mavinoo/laravel-batch/tests

Donate

BTC Address: 16XDxkcqiEJ8DYf4xWxu7WK3Peo29TvXxD

Comments
  • Not compatible Composer v2

    Not compatible Composer v2

    Deprecation Notice: Class Mavinoo\LaravelBatch\Batch located in ./vendor/mavinoo/laravel-batch/src/LaravelBatch.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0

    opened by lkmadushan 12
  •  Class 'Mavinoo\LaravelBatch\LaravelBatchServiceProvider' not found

    Class 'Mavinoo\LaravelBatch\LaravelBatchServiceProvider' not found

    Hi im having this error in Laravel:

    php artisan optimize In ProviderRepository.php line 208:

    Class 'Mavinoo\LaravelBatch\LaravelBatchServiceProvider' not found

    Script php artisan optimize handling the post-update-cmd event returned with error code 1

    opened by salvadorcea 9
  • Class 'Batch' not found

    Class 'Batch' not found

    I have added to aliases and providers in app.php but it does not seem to work.

    My code:

    public function storeBanks($request) {
    	$selected = $this->getListOfSelectedBanksIds();
    	return Batch::update('bank_school', $this->createUpdateBankObject($request, $selected));
    }
    
    
    opened by Cholowao 9
  • Publish a new release with Batch problem solved

    Publish a new release with Batch problem solved

    {
        "message": "Class 'Mavinoo\\LaravelBatch\\Batch' not found",
        "exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
        "file": "/home/vagrant/code/xxxxxxx-core/vendor/mavinoo/laravel-batch/src/LaravelBatchServiceProvider.php",
        "line": 16
    ....
    }
    

    I saw that you have fixed the "Batch" class problem on the ServiceProvider in the master branch. Can you publish a new release with this fix so we can establish a fixed version for our projects?

    Thanks.

    opened by alrik11es 7
  • How to get updated instance

    How to get updated instance

    use App\Models\User;
    
    $userInstance = new User;
    $value = [
         [
             'id' => 1,
             'status' => 'active',
             'nickname' => 'Mohammad'
         ] ,
         [
             'id' => 5,
             'status' => 'deactive',
             'nickname' => 'Ghanbari'
         ] ,
    ];
    $index = 'id';
    Batch::update($userInstance, $value, $index);
    

    After Batch::update, I want to access updated objects., like this:

    $updatedUser=Batch::update($userInstance, $value, $index);
    $updatedUser->where('country','UK')->get();
    

    But $updatedUser is a total number of updated array, so what can I do? Thank you~

    opened by dododaphne 4
  • NULL gets replaced with

    NULL gets replaced with ""

    I believe the update function replaces null values with "" (an empty string), which leads to sql errors; can't assign"" to an INT column, for example.

    opened by valivvvv 4
  • Syntax error, unexpected token

    Syntax error, unexpected token "return" :: 275 line

    Before 2.3.2 update laravel-btach works ok, now i'm getting error: syntax error, unexpected token "return"

    about this line: ...../vendor/mavinoo/laravel-batch/src/Batch.php:275 https://plik24.ovh/zrzut_ekranowy/220427_115042_5960.png

    opened by bizvid 3
  • syntax error, unexpected 'return' (T_RETURN)

    syntax error, unexpected 'return' (T_RETURN)

    When I try to run Batch:update method, error message shown like below;

    Laravel Framework 8.83.9

    ParseError                                                                                                            
                                                                                                                            
     syntax error, unexpected 'return' (T_RETURN)                                                                           
                                                                                                                            
     at C:\www\myapp\vendor\mavinoo\laravel-batch\src\Batch.php:275
       271▕     {                                                                                                           
       272▕         // no need for the old validation since we now use type hint that supports from php 7.0                 
       273▕         // but I kept this one                                                                                  
       274▕         if (count($columns) !== count(current($values)) {
     ➜ 275▕             return false;
       276▕         }
       277▕
       278▕         $query = [];
       279▕         $minChunck = 100;
    
    
    opened by tanero 3
  • ParseError: syntax error, unexpected 'return' (T_RETURN) in version 2.3.2, 2.3.3.

    ParseError: syntax error, unexpected 'return' (T_RETURN) in version 2.3.2, 2.3.3.

    You probably already know, but updating the package version to 2.3.2 or 2.3.3 generates the next error:

    ParseError: syntax error, unexpected 'return' (T_RETURN)
    in /vendor/mavinoo/laravel-batch/src/Batch.php:275
    

    I had to set the package to version 2.3.1 to avoid that error. Btw awesome package. Thanks

    opened by eleazarbr 3
  • Increment multiple values?

    Increment multiple values?

    Is there something available to increment multiple values like this?

    $userInstance = new \App\Models\User;
    $values = [
        [
            'id' => 4,
            'balance' => 'balance + 5',
        ],
        [
            'id' => 5,
            'balance' => \DB::raw('balance + 200'), // This works for the "->update" method
        ]
    ];
    $index = 'id';
    Batch::update($userInstance, $values, $index);
    
    opened by WalterWoshid 3
  • Call to undefined function Mavinoo\Batch\now()  in Batch.php line 242

    Call to undefined function Mavinoo\Batch\now() in Batch.php line 242

    Hi there,

    This package used to work fine for version 2.1, but I have recently run into the following error.

    I have tried to install version 2.2 but I still getting the following error that the following function is undefined. now().

    When I tried to update now()->format($table->getDateFormat()) to date($table->getDateFormat()) on line 67 and 242 of Batch.php it seems to work fine. Is this a solution as the database entries looks good.

    opened by salmonerasmus 3
  • Update rows with single quote

    Update rows with single quote

    Hello there! I try use this package for updating rows with fields which contains single quote. For example: files/'test 'Р'усс"кие "ry'bub".png. And i get an error: Syntax error: 7 ERROR: syntax error at or near \"test\"\nLINE 1: ...e\" SET \"name\" = (CASE WHEN fileid = '797' THEN '\\'test \\'Р\\'...\n .

    How can i solve this problem?

    opened by NikolayIlichev 0
  • how to update with pivot tables?

    how to update with pivot tables?

    Hello this is the following update method:

    `public function updateProfile(ProfileRequest $request, Profile $profile) { try { \DB::beginTransaction();

            $profile = new Profile;
    
            $input = [
                $this->profileInput(),
            ];
    
            $index = 'id';
    
            /** @var Mavinoo\Batch\Batch $batch */
            $batch = batch();
            $batch->update($profile, $input, $index);
            
    
            \DB::commit();
            session()->flash("message", ["success", __("<h5>Perfil actualizado</h5>")]);
            return redirect(route('profile', ['profile' => $profile]));
        } catch (\Throwable $exception) {
            \DB::rollBack();
            session()->flash("message", ["danger", $exception->getMessage()]);
            return back();
        }
    }`
    

    A new profile create, I have an array of a many to many relationship, for that relationship is saved in the database in the store method, i have:

    $profile->hobbies()->sync(request("hobbies"));

    putting that line of code in the update method gives me the following error:

    SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'profile_id' cannot be null (SQL: insert into category_profile (category_id, profile_id) values (1, ?))

    how can i solve it?

    opened by Nemachtilli 0
  • PHP 7.4 run Batch::update syntax error Batch.php:275

    PHP 7.4 run Batch::update syntax error Batch.php:275

    PHP 7.4.15 (cli) (built: Feb 16 2021 01:48:03) ( NTS )

    production.ERROR: syntax error, unexpected 'return' (T_RETURN) {"exception":"[object] (ParseError(code: 0): syntax error, unexpected 'return' (T_RETURN) at /back_end/vendor/mavinoo/laravel-batch/src/Batch.php:275)

    https://github.com/mavinoo/laravelBatch/blob/master/src/Batch.php#L275

    opened by puzzle9 0
  • Batch::update without index

    Batch::update without index

    Hi, I have massive data from external API, and to avoid duplicates, I need to use update instead of insert.SO the idea is to insert the data if it does not exist and update it instead if exists. My question is, is it possible without using an index?

    Regards

    opened by ianrussel 0
  • How set NULL?

    How set NULL?

    I have:

    [ [ "id" => "40142" "invoice_number" => null ], [ "id" => "40108" "invoice_number" => "555" ] ]

    Case with null - don't work. How can i insert null in batch update process?

    opened by bizvid 0
Releases(v2.3.5)
Owner
Mohammad Ghanbari
Web Application Developer
Mohammad Ghanbari
A Laravel package to output a specific sql to your favourite debugging tool. The supported log output is Laravel Telescope, Laravel Log, Ray, Clockwork, Laravel Debugbar and your browser.

Laravel showsql A Laravel package to output a specific sql to your favourite debugging tool, your browser or your log file. Use case You often want to

Dieter Coopman 196 Dec 28, 2022
TO DO LIST WITH LOGIN AND SIGN UP and LOGOUT using PHP and MySQL please do edit the _dbconnect.php before viewing the website.

TO-DO-LIST-WITH-LOGIN-AND-SIGN-UP TO DO LIST WITH LOGIN AND SIGN UP and LOGOUT using PHP and MySQL please do edit the _dbconnect.php before viewing th

Aniket Singh 2 Sep 28, 2021
MOP is a php query handling and manipulation library providing easy and reliable way to manipulate query and get result in a fastest way. ( WEBSITE VERSION )

Mysql Optimizer mysql optimizer also known as MOP is a php query handling and manipulation library providing easy and reliable way to manipulate query

null 3 Feb 14, 2022
phpMyFAQ - Open Source FAQ web application for PHP and MySQL, PostgreSQL and other databases

phpMyFAQ 3.1 What is phpMyFAQ? phpMyFAQ is a multilingual, completely database-driven FAQ-system. It supports various databases to store all data, PHP

Thorsten Rinne 547 Dec 27, 2022
A simple and extensible fixture loader for PHP 7.3+, supporting SQLite and MySQL

Flowder Flowder is a (really) simple fixture loader for PHP 7.3+, supporting SQLite and MySQL. Using Flowder in PHP 7.2 or below? Try version 1 instea

Joe Haines 6 Jan 17, 2021
Connect and work with MySQL/MariaDB database through MySQLi in PHP. This is an introductory project, If you need a simple and straightforward example that takes you straight to the point, you can check out these examples.

First MySQLi PHP Connect and work with MySQL/MariaDB database through MySQLi in PHP. The above exercises are designed for students. This is an introdu

Max Base 4 Feb 22, 2022
Online Navaratri Anjali and Bhog booking system. admin and user side.

Online-Navaratri-booking-php-project This online navaratri booking system integrate with razorpay and written on PHP, html and javascript. User PAGE U

Narayan Pote 1 Nov 19, 2021
Staggered import of large and very large MySQL Dumps even through the web servers with hard runtime limit and those in safe mode.

Staggered import of large and very large MySQL Dumps (like phpMyAdmin dumps) even through the web servers with hard runtime limit and those in safe mode. | Persian Translation Version

Amir Shokri 5 Jan 8, 2022
Clean up your Magento database by removing orphaned, unused and wrongly added attribute, attribute values and settings (for M2).

Magento 2 EAV Cleaner Console Command Purpose of this project is to check for different flaws that can occur due to EAV and provide cleanup functions.

FireGento e. V. - Hackathons 41 Dec 14, 2022
A simple library to access and manipulate database records. Built on top of Dibi and hardwired for PostgreSQL.

grifart/tables A simple library to access and manipulate database records. Built on top of Dibi and hardwired for PostgreSQL. This library is develope

GRIFART 5 Nov 11, 2022
This package provides a framework-agnostic database backup manager for dumping to and restoring databases from S3, Dropbox, FTP, SFTP, and Rackspace Cloud

Database Backup Manager This package provides a framework-agnostic database backup manager for dumping to and restoring databases from S3, Dropbox, FT

Backup Manager 1.6k Dec 23, 2022
A drop-in Doctrine ORM 2 implementation for Laravel 5+ and Lumen

Laravel Doctrine ORM A drop-in Doctrine ORM 2 implementation for Laravel 5+ $scientist = new Scientist( 'Albert', 'Einstein' ); $scientist->a

Laravel Doctrine 777 Dec 17, 2022
A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Laravel MongoDB This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. This library ex

Jens Segers 6.3k Jan 5, 2023
A Redis based, fully automated and scalable database cache layer for Laravel

Lada Cache A Redis based, fully automated and scalable database cache layer for Laravel Contributors wanted! Have a look at the open issues and send m

Matt 501 Dec 30, 2022
Laravel Thermite is an extended PostgreSQL Laravel database driver to connect to a CockroachDB cluster.

Laravel Thermite Laravel Thermite is an extended PostgreSQL Laravel database driver to connect to a CockroachDB cluster. ?? Supporting If you are usin

Renoki Co. 9 Nov 15, 2022
This project is about import CSV to Laravel with Laravel Excel library.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Abraham Víctor Zaragoza Rodríguez 1 Nov 20, 2021
🎩✨🌈 OOP Proxy wrappers utilities - generates and manages proxies of your objects

Proxy Manager This library aims to provide abstraction for generating various kinds of proxy classes. Documentation You can learn about the proxy patt

Marco Pivetta 4.8k Dec 29, 2022
A lightweight nearly-zero-configuration object-relational mapper and fluent query builder for PHP5.

Idiorm http://j4mie.github.com/idiormandparis/ Feature/API complete Idiorm is now considered to be feature complete as of version 1.5.0. Whilst it wil

Jamie Matthews 2k Dec 27, 2022
ORM layer that creates models, config and database on the fly

RedBeanPHP 5 RedBeanPHP is an easy to use ORM tool for PHP. Automatically creates tables and columns as you go No configuration, just fire and forget

Gabor de Mooij 2.2k Jan 9, 2023