robertbaelde / laravel_read_only_fields
Protect read only fields from accidentally being updated
Requires
- php: ^7.4|^8.0
Requires (Dev)
- brianium/paratest: ^6.2
- nunomaduro/collision: ^5.3
- orchestra/testbench: ^6.15
- phpunit/phpunit: ^9.3
This package is auto-updated.
Last update: 2025-02-05 03:47:36 UTC
README
Laravel read only fields lets you guard fields against unexpected updates.
An example use case for this might be when a projector in an event sourced system updates a read model. You want to make sure that the read model only gets updated by the projector.
Guarding fields on a model
To guard fields use the HasReadOnlyFields
trait in your model, and specify the read only fields by creating an array on your model named $readOnlyFields
use Illuminate\Database\Eloquent\Model; use Temperworks\ReadOnlyFields\HasReadOnlyFields; class YourModel extends Model { use HasReadOnlyFields; protected array $readOnlyFields = [ 'read_only_field' ]; }
Updating read only fields
When you want to update a read only field, you can mark that you intend to update the field by using writable(['read_only_field'])
.
After the model is saved, the writable state is reset.
$model = YourModel::find(1); $model->writable(['read_only_field'])->update(['read_only_field' => 'foo']); // this will throw an exception since we already updated the model. $model->update(['read_only_field' => 'foobar']);
Credits
License
The MIT License (MIT). Please see License File for more information.