PHP code example of ssntpl / data-fields

1. Go to this page and download the library: Download ssntpl/data-fields 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/ */

    

ssntpl / data-fields example snippets


use Ssntpl\DataFields\Support\DataField;

class User extends Model
{
    protected $casts = [
        'preferences' => DataField::class,    // cast mode
    ];
    use \Ssntpl\DataFields\Concerns\HasDataFields;   // row mode
}

// Cast mode — work with the column as a typed document
$user->preferences = DataField::section(items: [
    ['key' => 'dark_mode', 'type' => 'bool', 'value' => true],
    ['key' => 'language',  'type' => 'text', 'value' => 'en'],
]);
$user->preferences->dark_mode->value;   // bool true
$user->preferences->dark_mode->value = false;
$user->save();

// Row mode — store fields polymorphically
$user->fields()->create([
    'key' => 'phone', 'type' => 'text', 'value' => '+91-9999900000',
]);
$user->getFieldValue('phone');          // '+91-9999900000'

Schema::table('users', function (Blueprint $table) {
    $table->json('preferences')->nullable();
});

   Schema::table('users', function (Blueprint $table) {
       $table->json('preferences')->nullable();
   });
   

   use Ssntpl\DataFields\Support\DataField;

   class User extends Model
   {
       protected $casts = [
           'preferences' => DataField::class,
       ];

       protected $fillable = ['preferences', /* ... */];
   }
   

protected $casts = [
    'preferences'       => DataField::class,
    'email_settings'    => DataField::class,
    'shipping_defaults' => DataField::class,
];

use Ssntpl\DataFields\Support\DataField;

$user->preferences = DataField::section(items: [
    ['key' => 'dark_mode', 'type' => 'bool', 'value' => true],
    ['key' => 'language',  'type' => 'text', 'value' => 'en'],
]);
$user->save();

$user->preferences = [
    'type'  => 'section',
    'items' => [
        ['key' => 'dark_mode', 'type' => 'bool', 'value' => true],
    ],
];
$user->save();

$user->preferences = null;
$user->save();

$user->preferences->dark_mode;          // DataField (leaf)
$user->preferences->dark_mode->value;   // bool true (cast via the field's type)
$user->preferences->language->value;    // 'en'

$user->preferences->appearance->dark_mode->value;

$user->preferences->dataField('appearance.dark_mode')->value;

$user->preferences->missing_key;        // null

$user->preferences->dark_mode->value = false;
$user->save();

$user->preferences->dark_mode = DataField::leaf('bool', false, ['key' => 'dark_mode']);
// or, equivalently, with a plain array:
$user->preferences->dark_mode = ['key' => 'dark_mode', 'type' => 'bool', 'value' => false];
$user->save();

$user->preferences->addField([
    'key' => 'fontsize', 'type' => 'number', 'value' => 14,
]);

$user->preferences->removeField('language');

$user->save();

$user->preferences = DataField::section(items: [
    [
        'type' => 'group', 'key' => 'appearance', 'label' => 'Appearance',
        'items' => [
            ['key' => 'dark_mode', 'type' => 'bool', 'value' => true],
            ['key' => 'accent', 'type' => 'select_single', 'value' => 'blue',
             'options' => [['key' => 'blue'], ['key' => 'red']]],
        ],
    ],
    [
        'type' => 'group', 'key' => 'notifications', 'label' => 'Notifications',
        'items' => [
            ['key' => 'frequency', 'type' => 'select_single', 'value' => 'daily',
             'options' => [['key' => 'daily'], ['key' => 'weekly']]],
        ],
    ],
]);

$user->preferences->appearance->dark_mode->value;
$user->preferences->dataField('appearance.accent')->value;
$user->preferences->notifications->frequency->value;

$user->preferences = DataField::section(items: [
    ['key' => 'name', 'type' => 'text', 'validations' => ['   $user->preferences->validate();
} catch (\Illuminate\Validation\ValidationException $e) {
    // $e->errors() — dotted paths, e.g. 'step_1.age' for nested
}

static::saving(function ($model) {
    if ($model->preferences) {
        $model->preferences->validate();
    }
});

$df = new DataField([
    'key' => 'plan', 'type' => 'text', 'default' => 'free',
]);
$df->value;                  // 'free' (from default)

$df->value = 'pro';
$df->value;                  // 'pro'

$df->value = null;
$df->value;                  // null (explicit override)

DataField::section(items: [
    ['key' => 'has_phone', 'type' => 'bool', 'value' => false],
    [
        'key' => 'phone', 'type' => 'text',
        'visible_if' => ['has_phone' => true],
        'validations' => ['

DataField::section(?string $key = null, array $items = [], array $extra = []): self
DataField::step(?string $key = null, array $items = [], array $extra = []): self
DataField::group(?string $key = null, array $items = [], array $extra = []): self
DataField::leaf(FieldType|string $type, mixed $value = null, array $extra = []): self
DataField::fromArray(array $node): self

use Ssntpl\DataFields\Support\DataField;
use Ssntpl\DataFields\Support\FieldType;

DataField::section('preferences', items: [...]);
DataField::leaf(FieldType::Date, '2026-06-15', ['key' => 'expires_at']);
DataField::leaf('number', 14, ['key' => 'fontsize', 'label' => 'Font size']);

foreach ($user->preferences as $field) {
    echo $field->key . ' = ' . $field->value . PHP_EOL;
}

count($user->preferences);          // count of items

$user->preferences[0];              // first DataField
$user->preferences['dark_mode'];    // DataField with key 'dark_mode'
unset($user->preferences['dark_mode']);

use Ssntpl\DataFields\Concerns\HasDataFields;

class Product extends Model
{
    use HasDataFields;
}

$product->fields()->create([
    'key'   => 'sku',
    'type'  => 'text',
    'value' => 'WIDGET-001',
    'label' => 'Stock keeping unit',
]);

// Read
$product->fields;                                      // Collection<DataRow>
$product->fields()->where('key', 'sku')->first()->value;

// Cast across all rows
foreach ($product->fields as $row) {
    echo $row->label . ' = ' . $row->value . PHP_EOL;
}

$product->getFieldValue('sku');                        // cast value or null
$product->setFieldValue('sku', 'NEW-001');             // upsert by key
$product->setFieldValue('weight', 2.5, 'number');      // type on first set

use Ssntpl\DataFields\Models\DataRow;

class CustomDataRow extends DataRow
{
    protected $extraFillable = ['source_system'];

    public function getFillable()
    {
        return array_merge(parent::getFillable(), $this->extraFillable ?? []);
    }

    public function isFromExternalSystem(): bool
    {
        return $this->source_system !== null;
    }
}

// config/data-fields.php
return [
    'data_row_model' => App\Models\CustomDataRow::class,
];

$product->fields()->create([
    'key'         => 'price',
    'value'       => '99.99',
    'type'        => 'number',
    'validations' => ['

use Ssntpl\DataFields\Support\FieldType;

FieldType::Bool->value;              // 'bool'
FieldType::SelectSingle->isLeaf();   // true
FieldType::Section->isContainer();   // true

FieldType::leaves();                 // list of leaf cases
FieldType::containers();             // list of container cases

DataField::leaf(FieldType::DateTime, now(), ['key' => 'last_seen']);

$file = File::find(123);

$user->preferences = DataField::section(items: [
    ['key' => 'avatar', 'type' => 'file', 'value' => $file],
]);
$user->save();

$user->preferences->avatar->value;          // File instance
$user->preferences->avatar->value->url;     // works as any File

$user->preferences->addField([
    'key' => 'attachments', 'type' => 'files',
    'value' => [$f1, $f2, $f3],
]);

$user->preferences->attachments->value;     // array<File>

return [
    // Row-mode Eloquent model. Subclass DataRow and point at it to add
    // custom attributes/behaviour.
    'data_row_model' => \Ssntpl\DataFields\Models\DataRow::class,

    // Enable created_at / updated_at on the `data_fields` table.
    // Off by default — most consumers don't need per-row timestamps.
    'data_fields_timestamps' => false,

    // When true, the service provider loads the package's migration
    // directly — no `vendor:publish` needed.
    'auto_load_migrations' => false,
];

static::creating(function (User $user) {
    if ($user->preferences === null) {
        $user->preferences = DataField::section(items: [
            ['key' => 'language', 'type' => 'text', 'value' => 'en'],
            ['key' => 'theme',    'type' => 'select_single', 'value' => 'system',
             'options' => [['key'=>'system'],['key'=>'light'],['key'=>'dark']]],
        ]);
    }
});

static::saving(function (User $user) {
    if ($user->preferences) {
        $user->preferences->validate();
    }
});

$walker = function (DataField $node) use (&$walker, &$leaves) {
    if ($node->isLeaf()) {
        $leaves[] = $node;
        return;
    }
    foreach ($node->items as $child) {
        $walker($child);
    }
};
$leaves = [];
$walker($user->preferences);

use Ssntpl\DataFields\Traits\HasDataFieldsJson;

class LogEntry extends Model
{
    use HasDataFieldsJson;
}

$entry->setDataFieldsSchema([
    ['key' => 'performed_by', 'type' => 'text'],
]);
$entry->setFieldValue('performed_by', 'Rahul');
$entry->save();

use Ssntpl\DataFields\Support\DataField;

class LogEntry extends Model
{
    protected $casts = [
        'entry_data' => DataField::class,
    ];
}

$entry->entry_data = DataField::section();
$entry->entry_data->addField(['key' => 'performed_by', 'type' => 'text', 'value' => 'Rahul']);
$entry->save();
bash
php artisan vendor:publish --tag=data-fields-config
bash
php artisan vendor:publish --tag=data-fields-migrations
php artisan migrate