1. Go to this page and download the library: Download brighten/immutable-model library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
brighten / immutable-model example snippets
use Brighten\ImmutableModel\ImmutableModel;
class UserView extends ImmutableModel
{
protected string $table = 'user_views';
protected ?string $primaryKey = 'id';
protected array $casts = [
'settings' => 'array',
'created_at' => 'datetime',
];
}
// Query just like Eloquent
$users = UserView::where('active', true)->get();
$user = UserView::find(1);
$user = UserView::with('posts')->first();
// In-memory changes are allowed (for computed fields, API responses, etc.)
$user->computed_field = 'some value'; // Works fine
$user->name = 'Modified'; // Works fine (in-memory only)
// But database persistence is blocked
$user->save(); // Throws ImmutableModelViolationException
$user->update([...]); // Throws ImmutableModelViolationException
$user->delete(); // Throws ImmutableModelViolationException
UserView::create([...]); // Throws ImmutableModelViolationException
// Chunk for batch processing
MyModel::chunk(1000, function ($models) {
foreach ($models as $model) {
// Process
}
});
// Cursor for memory-efficient iteration
foreach (MyModel::cursor() as $model) {
// Process one at a time
}
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class TenantScope implements Scope
{
public function apply(Builder $builder, Model $model): void
{
$builder->where('tenant_id', auth()->user()->tenant_id);
}
}
class TenantModel extends ImmutableModel
{
protected static function booted(): void
{
static::addGlobalScope(new TenantScope);
}
}
// Bypass scopes when needed
TenantModel::withoutGlobalScopes()->get();
TenantModel::withoutGlobalScope(TenantScope::class)->get();