Insert Multiple record in Laravel |websolutioncode.com
Insert Multiple record in Laravel |websolutioncode.com

laravel insert multiple records example

Introduction

In this Laravel tutorial, discover how to insert multiple records into a database table seamlessly using the Eloquent ORM (Object-Relational Mapping) or the query builder. Eloquent simplifies database interactions with PHP syntax, offering a clear example of Laravel insert multiple records.

Let’s go through the process of inserting multiple records into a database table using Eloquent in Laravel. We’ll assume you have a model named YourModel corresponding to the database table and a controller where you want to perform the insertion.

Create Model:

First, ensure you have a model for the table you want to insert records into. If you don’t have one, create it using the Artisan command:

php artisan make:model YourModel

Define Fillable Fields:

In your YourModel.php file, specify the fillable fields that can be mass-assigned. For example:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class YourModel extends Model
{
    protected $fillable = ['field1', 'field2', 'field3'];
}

Controller Code:

In your controller, use the create method to insert multiple records. For example:

<?php

namespace App\Http\Controllers;

use App\YourModel;

class YourController extends Controller
{
    public function insertRecords()
    {
        $records = [
            ['field1' => 'value1', 'field2' => 'value2', 'field3' => 'value3'],
            ['field1' => 'value4', 'field2' => 'value5', 'field3' => 'value6'],
            // Add more records as needed
        ];

        YourModel::insert($records);

        return "Records inserted successfully!";
    }
}

Route:

Don’t forget to define a route for your controller method in the web.php file or in the api.php file, depending on your application.

// routes/web.php or routes/api.php

use App\Http\Controllers\YourController;

Route::get('/insert-records', [YourController::class, 'insertRecords']);

Run the Code:

Visit the URL associated with your route in a browser or through an API request to execute the insertRecords method.

In the provided example, the insert method is used to insert multiple records at once. This method is efficient for bulk inserts and reduces the number of database queries.

Check our tools website Word count
Check our tools website check More tutorial

Leave a Reply