This package will add insertAsModel
macro to Laravel's Eloquent Builder class.
Unlike insert
, insertAsModel
method will ensure that all inserted values will go through models' casts and mutators then it will just pass it to the insert
method.
You can install the package via composer:
composer require laravel-macros/eloquent-insert-as-model
Assuming you have:
class User extends Model
{
protected $casts = [
'options' => 'json',
'shelf' => 'collection',
];
}
Normally if you will use the Model::insert
method to insert a batch of entries, casts and mutators will be ignored and you will have to stringify the values yourself.
Using this package, you can insert values the same way you use Model::create
, where all the proper casting and mutating logic will be applied.
User::insertAsModel([
[
'options' => ['sms' => true],
'shelf' => collect(['book1', 'book2', 'book3']),
],
[
'options' => ['sms' => false],
'shelf' => collect(['book1', 'book2']),
],
]);
This will prevent you from doing hacks like 'options' => json_encode(['sms' => true])
.
Note:
insertAsModel
is not a multiplecreate
calls. It will insert entries directly to the database (just likeinsert
). For example it won't fire models events.
composer test
# Test Coverage with XDebug enabled
composer test-coverage
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.