How to insert multiple rows in mysql using loop in laravel?

Created at 04-Aug-2021 , By samar

How to insert multiple rows in mysql using loop in laravel?

In this session, we will try our hand at solving the "How to insert multiple rows in mysql using loop in laravel?".

You can insert multiple rows in MySQL using foreach loop in laravel. You can get the records (values) in an array and you can insert the value in the table using foreach iteration
  • Insert multiple records using foreach in laravel

    $timezones = ['(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi', '(UTC-12:00) International Date Line West', 'UTC-11:00) Midway Island, Samoa'] ;
    
    foreach($timezones as $timezone){
        Timezone::create([
            'name' => $timezone,
        ]);
    }
    
    //Import Timezone model before class definition
    use App\Models\Timezone;
    

    This code snippet example is helpful when you want to insert multiple records in a single execution.

  • Insert multiple records with multiple columns in table using laravel eloquent

    //Controller's method to insert records in the table
    public function insertSalaryRecords(){
        $emp_details = array(
            array("emp_id" => 4, "emp_name"=> 'samarjeet kumar', "basic_sal" => 21000),
            array("emp_id" => 5, "emp_name"=> 'sonu chauhan', "basic_sal" => 25000),
            array("emp_id" => 6, "emp_name"=> 'manoj singh', "basic_sal" => 27000)
        );
        
        $new_insert_array=array();
        foreach($emp_details as $key=>$val)
        {
            $new_insert_array[]=array('emp_id'=>$val['emp_id'],'emp_name'=>$val['emp_name'],'basic_sal'=>$val['basic_sal']);
        }
        Salary::insert($new_insert_array);
    
        echo "data inserted";
    }
    
    
    //Create model and table structure using migration command
    php artisan make:model Salary -m
    
    //Migration file content - database/migrations/<2021_08_04_115521>_create_salaries_table.php
    Schema::create('salaries', function (Blueprint $table) {
        $table->id();
        $table->integer('emp_id');
        $table->string('emp_name');
        $table->bigInteger('basic_sal');
        $table->timestamps();
    });
    
    //Create salary controller
    php artisan make:controller SalaryController
    
    //RouteĀ 
    Route::get('/insert-salaries', 'SalaryController@insertSalaryRecords');
    

    You can insert multiple records with multiple columns in table using laravel eloquent

  • Upsert() method in laravel

    DB::table('users')->upsert([
        ['id' => 1, 'email' => 'taylor@example.com'],
        ['id' => 2, 'email' => 'dayle@example.com'],
    ], ['email']);
    

    The first argument is the values to insert/update the records and the second argument is the column(s) that uniquely identify records. All databases except SQL Server require these columns to have a PRIMARY or UNIQUE index.

    It will insert the record if the value does not already exist in the database else it will update the records. The upsert method will automatically set the created_at and updated_at timestamps if timestamps are enabled on the model.

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.