Eloquent ORM

Laravel Eloquent ORM

Attribute

Default Fields Attribute Value

https://laravel.com/docs/9.x/eloquent#default-attribute-values

class Post extends Model
{
    $attributes = [
        'meta' => '[]',
        'is_published' => true,
    ];

    $casts = [
        'meta' => 'array',
        'is_published' => 'boolean',
    ];
}

Insert

Bulk Insertion in Laravel using eloquent ORM

vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php

https://laravel.com/api/9.x/Illuminate/Database/Eloquent/Factories/Factory.html

Method 1: Eloquent insert function

You can use the Eloquent::insert() function to bulk insert your data.

But it doesn’t auto-generate the created_at and updated_at timestamp when you use the Eloquent::insert() function, so you have to generate the timestamp by yourself.

If you are using Eloquent $casts property to transform database data from json to array format. The Eloquent::insert() function doesn’t help you to transform these json field data, so you have to encode the data from array to json by yourself.

// Eloquent::insert()
$NowCarbon = Carbon::now();

$user_list = [
    [
        'name'=>'Kay',
        'age'=>18,
        'meta' => [
            'is_admin' => false
        ],
    ],
    [
        'name'=>'Jay',
        'age'=>18,
        'meta' => [
            'is_admin' => false
        ],
    ],
    [
        'name'=>'KJ',
        'age'=>18,
        'meta' => [
            'is_admin' => true
        ],
    ],
];

foreach($user_list as &$user) {
    $user['meta'] = json_encode($user['meta']);
    $user['created_at'] = $NowCarbon;
    $user['updated_at'] = $NowCarbon;
}

UserModel::insert($user_list);

Method 2: More Eloquent way

$user_list = [];
foreach($candidate_users as $user){ // $interests array contains input data
    $interestcat = new UserModel();
    $interestcat->name = $user->name;
    $interestcat->age = $user->age;
    $user_list[] = $interestcat->attributesToArray();
}
UserModel::insert($user_list);

Method 3: DB insert function

DB::table('user')->insert($user_list);

Reference

Official

Attribute

Insert


Attribute

Laravel Eloquent ORM Attribute

Join

Laravel Eloquent ORM Join

Relationships

Laravel Eloquent ORM Relationships

Mutators & Casting

Laravel Eloquent ORM Mutators & Casting

Factory

Laravel Eloquent ORM Factory

Lazy Collection

Laravel Eloquent ORM Lazy Collection