All packages
Attributes for Laravel
Per-model schemas
A model can declare its own definitions, merged over the global ones for that model only. Declare a $attributeDefinitions property:
class Product extends Model implements HasAttributesContract
{
use HasAttributes;
/** @var array<string, array<string, mixed>> */
protected array $attributeDefinitions = [
'rating' => ['type' => 'integer', 'rules' => ['min:1', 'max:5'], 'required' => true],
'sku' => ['type' => 'string', 'unique' => 'global'],
'token' => ['type' => 'string', 'encrypted' => true],
'retries' => ['type' => 'integer', 'default' => 3],
];
}…or a public attributeDefinitions() method, handy when the schema is computed:
class Ticket extends Model implements HasAttributesContract
{
use HasAttributes;
/**
* @return array<string, array<string, mixed>>
*/
public function attributeDefinitions(): array
{
return [
'priority' => ['type' => 'integer', 'rules' => ['min:1', 'max:4'], 'required' => true],
'escalated_at' => ['type' => 'datetime'],
'channel' => ['type' => 'string', 'default' => 'email'],
];
}
}How schemas merge
Attributes::define(new AttributeDefinitionData('retries', AttributeType::Integer, default: 99));
$product->attributeInt('retries'); // 3 — Product declares its own default
$order->attributeInt('retries'); // 99 — Order falls back to the global definition
Attributes::definitionsFor($product); // global definitions overlaid by Product's own- A model-declared definition overrides a same-named global definition — for that model only; other models keep the global one.
- Entries use the same keys as the definitions config: type, rules, required, default, unique and encrypted.
- When a model declares both, the method wins over the property.
- They are parsed exactly like the config entries, so a non-array entry or a typo’d key throws InvalidConfigurationException naming App\Models\Product::attributeDefinitions.<name>.<key>.
- Strict mode, validation, the stored type, encryption, uniqueness, defaults and validateAttributes() all honour the model’s schema.
Show your open-source love
This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.
More ways to support, including cryptoBy donating, you agree to our donation terms.
Want this built into your product?
We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.