dylan-chapman/immutability

A simple Laravel package that allows you to enforce immutable attributes on Eloquent models.
8,907
Install
composer require dylan-chapman/immutability
Latest Version:0.5
PHP:>=7.2
License:MIT
Last Updated:Jan 25, 2023
Links: GitHub  ·  Packagist
Maintainer: Dylan-Chapman

Immutability

Immutability is a simple package that is used in your Eloquent models to enforce attribute immutability. Immutable attributes may be set, and changed once, but once the model is saved, the value can not be changed.

License

Immutability is open-sourced software licensed under the MIT license

Installation

To get started with Immutability, add to your composer.json file as a dependency:

composer require dylan-chapman/immutability

Basic Usage

To use the Immutability library, you simply need to use the Immutability trait for any model you wish to identify immutable attributes for. Typically, you would want to implement the trait in your super-class so that all your sub-classes will automatically inherit the functionality.

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;
use Eloquent\Attributes\Immutability;

class MyAppSuperModel extends Model
{
    use Immutability;

    protected $immutable = ['id', 'uuid'];
}

Class override.

<?php
namespace App;

class User extends MyAppSuperModel
{
    protected $immutable = ['id', 'uuid', 'username'];
}

Catching exceptions

<?php
namespace App;

use Eloquent\Attributes\Exceptions\ImmutableFieldViolationException;
use Exception;

$user = User::find(1);

try {
    $user->username = "myNewUserName";
    $user->save();
} catch ( ImmutableFieldViolationException $e ) {
   // Handle immutable attribute violation error
} catch ( Exception $e ) {
   // Handle error
}

Related Packages

davidmpeace/immutability

A simple Laravel package that allows you to enforce immutable attributes on Eloq...

20,474 6
davidmpeace/squirrel

Laravel package that automatically caches and retrieves models when querying rec...

2,562 6
sofa/model-locking

Pseudo pessimistic model locking with broadcasted events for Laravel Eloquent OR...

48,175 47
stevenmaguire/laravel-cache

Seamlessly adding caching to Laravel service objects

1,758 17
nilportugues/serializer-eloquent

Eloquent Driver for NilPortugues Serializer outputting valid API responses in JS...

36,591 5