laravel-macros/eloquent-insert-as-model

This package is abandoned and no longer maintained. No replacement package was suggested.

Add `insertAsModel` macro to Eloquent Builder. Unlike `insert`, `insertAsModel` method will ensure that all inserted values will go through models' casts and mutators.

1.0.0 2021-04-25 12:38 UTC

This package is auto-updated.

Last update: 2022-05-20 10:31:15 UTC


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.

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

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 multiple create calls. It will insert entries directly to the database (just like insert). 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.