Simple package to decorate classes with field attributes, allowing you to easily convert data objects to forms with labels and descriptions.
You can install the package via composer:
composer require performing/laravel-field-attributesclass MyDto
{
use FieldAttributes;
public function __construct(
#[Field(label: 'Name', description: 'Enter your full name')]
public string $name,
#[Field(label: 'Email', description: 'Enter your email address')]
public string $email,
) {}
}
$instance = new MyDto('John Doe', 'john@example.com');
$instance->getFieldValues();
// ['name' => 'John Doe', 'email' => 'john@example.com']
$instance->getFieldDefinitions();
// [
// 'name' => ['label' => 'Name', 'description' => 'Enter your full name', 'type' => 'string', 'required' => true, 'value' => 'John Doe'],
// 'email' => ['label' => 'Email', 'description' => 'Enter your email address', 'type' => 'string', 'required' => true, 'value' => 'john@example.com']
// ]If you combine this with spatie/laravel-data, you can also add validation on top, serialize and deserialize as JSON back and forth from the database.
In the package there is also a caster ObjectCast which can cast a json column to an object, it takes the class name from a type column of the eloquent model. You can also map types to specifc classes in the config.
composer testThe MIT License (MIT). Please see License File for more information.