hareland/laravel-immutable-attributes

使Laravel模型属性不可变

v1.0.2 2024-05-26 18:51 UTC

README

Build Total Downloads

Laravel不可变模型属性

在您的Laravel模型上创建不可变属性。只需使用特性即可。

安装

要求:PHP 8.1+ 和 Laravel 8+

composer require hareland/laravel-immutable-attributes

定义不可变属性

在您的模型上定义要设置为不可变的属性

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
use Hareland\LaravelImmutableAttributes\Traits\HasImmutableAttributes;
 
class Product extends Model
{
    use HasImmutableAttributes;
    
    /**
     * @var array
     */
    protected $immutable = [
        'label',
        'price',
    ];

在这个例子中,labelprice 可以在模型创建时设置,但是属性值在更新时不会持久化到数据库。

$model = new Product;
 
// Set the attribute 
$model->label = 'abc';
$model->label; // 'abc'
 
// Change it (before-saving)
$model->label = 'abc';
$model->label; // 'abc'
 
// Save it
$model->save();
 
// You can't change its value
$model->label = 'xyz';
$model->label; // 'abc'
 
// You can't update it either
$model->save([
    'label' => 'xyz',
]);
$model->label; // 'abc'

"Buy Me A Coffee"