Attribute
Laravel Eloquent ORM Attribute
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',
];
}
vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php
https://laravel.com/api/9.x/Illuminate/Database/Eloquent/Factories/Factory.html
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);
$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);
DB::table('user')->insert($user_list);
Laravel Eloquent ORM Attribute
Laravel Eloquent ORM Join
Laravel Eloquent ORM Relationships
Laravel Eloquent ORM Mutators & Casting
Laravel Eloquent ORM Factory
Laravel Eloquent ORM Lazy Collection