robertbaelde/

laravel_read_only_fields

保护只读字段,防止意外更新

1.0.0 2021-04-15 10:00 UTC

This package is auto-updated.

Last update: 2024-09-05 02:47:02 UTC


README

GitHub Tests Action Status

Laravel read only fields 允许您保护字段免受意外更新。

此功能的一个示例用例可能是当事件源系统中的投影仪更新只读模型时。您想确保只读模型只能由投影仪更新。

保护模型中的字段

要保护字段,请在使用模型时使用 HasReadOnlyFields 特性,并通过在模型上创建名为 $readOnlyFields 的数组来指定只读字段。

use Illuminate\Database\Eloquent\Model;
use Temperworks\ReadOnlyFields\HasReadOnlyFields;

class YourModel extends Model
{
    use HasReadOnlyFields;

    protected array $readOnlyFields = [
        'read_only_field'
    ];
}

更新只读字段

当您想更新一个只读字段时,可以使用 writable(['read_only_field']) 标记您的意图更新该字段。模型保存后,可写状态将重置。

$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']);

致谢

许可协议

MIT 许可协议 (MIT)。有关更多信息,请参阅许可文件