laravel-macros / eloquent-insert-as-model
Add `insertAsModel` macro to Eloquent Builder. Unlike `insert`, `insertAsModel` method will ensure that all inserted values will go through models' casts and mutators.
Requires
- php: ^8.0
- illuminate/support: ^5.5 || ^6.0 || ^7.0 || ^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: dev-master
- orchestra/testbench: ^6.15
- phpunit/phpunit: ^9.3
README
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.
Installation
You can install the package via composer:
composer require laravel-macros/eloquent-insert-as-model
Usage
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.
Testing
composer test # Test Coverage with XDebug enabled composer test-coverage
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.