PHP code example of tobymaxham / laravel-properties

1. Go to this page and download the library: Download tobymaxham/laravel-properties 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/ */

    

tobymaxham / laravel-properties example snippets


class User extends Model
{
    use HasProperties;

    protected array $propertyDefaults = ['theme' => 'light', 'newsletter' => false];

    protected function propertyCasts(): array
    {
        return ['newsletter' => 'bool', 'plan' => Plan::class, 'api_token' => 'encrypted'];
    }
}

$user->getProperty('theme');                   // 'light' (default, nothing stored)
$user->setProperty('plan', 'pro')->save();     // stored as "pro"
$user->getProperty('plan');                    // Plan::Pro

User::whereProperty('plan', Plan::Pro)->get();
User::whereProperty('newsletter', false)->get(); // also finds users without the property

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->properties(); // json('properties')->nullable()
    $table->timestamps();
});

use Illuminate\Database\Eloquent\Model;
use TobyMaxham\LaravelProperties\HasProperties;

class User extends Model
{
    use HasProperties;
}

$user->setProperty('ui.theme', 'dark');
$user->setProperties(['ui.size' => 'lg', 'newsletter' => true]); // keeps the other properties
$user->save();

$user->getProperty('ui.theme');            // 'dark'
$user->getProperty('ui');                  // ['theme' => 'dark', 'size' => 'lg']
$user->getProperty('missing', 'fallback'); // 'fallback' (also as closure: fn () => ...)
$user->hasProperty('ui.size');             // true

$user->getProperties();                    // all properties, merged with the defaults
$user->getStoredProperties();              // only what is stored, without defaults and casts
$user->onlyProperties(['ui.theme', 'newsletter']);
$user->exceptProperties('ui');

$user->forgetProperty('ui.size');          // or an array of keys
$user->replaceProperties(['theme' => 'dark']);
$user->clearProperties();                  // stored as {}

$user->pushProperty('tags', 'laravel', 'php');
$user->pullProperty('legacy');             // get and remove
$user->incrementProperty('logins');        // decrementProperty('credits', 5)
$user->toggleProperty('newsletter');

$props = $user->props();

$props->theme;                  // like getProperty('theme')
$props->theme = 'dark';         // like setProperty('theme', 'dark')
$props['ui.size'];              // array access with "dot" notation
unset($props['legacy']);
isset($props->theme);

$props->set('theme', 'dark')->set(['ui.size' => 'lg'])->increment('logins');
$props->get('ui.size', 'md');
$props->all();                  // with defaults and casts
$props->stored();               // without defaults and casts
$props->collect();              // as Collection
count($props);
foreach ($props as $key => $value) { /* ... */ }
json_encode($props);

use TobyMaxham\LaravelProperties\Enums\PropertiesCast;

class User extends Model
{
    use HasProperties;

    public const string PROPERTIES_COLUMN = 'settings';

    public const PropertiesCast PROPERTIES_CAST = PropertiesCast::Object;
}

class User extends Model
{
    use HasProperties;

    protected array $propertyDefaults = [
        'theme' => 'light',
        'ui'    => ['size' => 'md', 'density' => 'normal'],
        'roles' => ['user'],
    ];
}

$user->setProperty('ui.size', 'lg');

$user->getProperty('theme');   // 'light'
$user->getProperty('ui');      // ['size' => 'lg', 'density' => 'normal']
$user->hasProperty('theme');   // true
$user->getStoredProperties();  // ['ui' => ['size' => 'lg']]

public const bool SERIALIZE_PROPERTY_DEFAULTS = true;  // always with defaults

$user->withPropertyDefaults()->toArray();              // this instance with defaults
$user->withoutPropertyDefaults()->toJson();            // this instance without defaults

use TobyMaxham\LaravelProperties\PropertyCasts\EnumCast;

protected function propertyCasts(): array
{
    return [
        'logins'          => 'int',
        'price'           => 'decimal:2',
        'newsletter'      => 'bool',
        'birthday'        => 'date',
        'starts_at'       => 'datetime:d.m.Y H:i',
        'plan'            => Plan::class,                    // backed enum
        'mood'            => EnumCast::lenient(Mood::class), // unknown values become null
        'address.country' => Country::class,                 // nested key
        'amount'          => MoneyCast::class.':EUR',        // custom cast with arguments
    ];
}

use Illuminate\Database\Eloquent\Model;
use TobyMaxham\LaravelProperties\Contracts\PropertyCast;

class MoneyCast implements PropertyCast
{
    public function __construct(private string $currency = 'EUR') {}

    public function get(mixed $value, string $key, Model $model): ?Money
    {
        return null === $value ? null : new Money($value, $this->currency);
    }

    public function set(mixed $value, string $key, Model $model): ?int
    {
        return match (true) {
            null === $value          => null,
            $value instanceof Money  => $value->cents,
            default                  => (int) round((float) $value * 100),
        };
    }
}

protected function propertyCasts(): array
{
    return [
        'api_token'   => 'encrypted',
        'pin'         => 'encrypted:int',
        'expires_at'  => 'encrypted:datetime',
        'level'       => 'encrypted:'.Level::class,
        'oauth.token' => 'encrypted',
    ];
}

$table->properties(encrypted: true);

public const PropertiesCast PROPERTIES_CAST = PropertiesCast::EncryptedArray;

User::whereProperty('theme', 'dark')->get();
User::whereProperty('logins', '>', 10)->orWhereProperty('plan', Plan::Pro)->get();
User::whereProperties(['theme' => 'dark', 'newsletter' => true])->get();

User::wherePropertyIn('plan', [Plan::Pro, Plan::Team])->get();
User::wherePropertyNotIn('theme', ['dark']);
User::wherePropertyNull('deleted_reason');
User::wherePropertyNotNull('ui.theme');
User::wherePropertyBetween('logins', [10, 100]);
User::wherePropertyNotBetween('birthday', ['2000-01-01', '2009-12-31']);

User::whereHasProperty('api_token');                 // the property exists (or has a default)
User::whereDoesntHaveProperty('legacy');
User::wherePropertyContains('roles', 'admin');       // or several: ['admin', 'editor']
User::wherePropertyDoesntContain('roles', 'banned');
User::wherePropertyLength('tags', '>', 2);           // or wherePropertyLength('tags', 3)

User::orderByProperty('logins', 'desc')->get();      // or orderByPropertyDesc('logins')

$table->properties();                         // json, nullable
$table->properties('settings', jsonb: true);  // jsonb on PostgreSQL
$table->properties('secrets', encrypted: true); // text, for encrypted columns
$table->dropProperties('settings');

$table->propertyIndex('ui.theme');                       // for whereProperty('ui.theme', ...)
$table->propertyIndex('plan', 'settings', name: 'plan_index');
$table->dropPropertyIndex('ui.theme');

use TobyMaxham\LaravelProperties\Properties;

Properties::table('users')                       // plain JSON, without model
    ->rename('theme', 'ui.theme')
    ->forget(['legacy_flag', 'old.key'])
    ->set('newsletter', false, onlyIfMissing: true)
    ->set('label', fn (array $properties, object $row) => "user-{$row->id}")
    ->transform('price', fn ($cents) => $cents / 100)
    ->where(fn ($query) => $query->where('active', true))
    ->run();

Properties::for(User::class)                     // with the casts and encryption of the model
    ->set('plan', Plan::Free, onlyIfMissing: true)
    ->set('api_token', fn () => Str::random(40))
    ->run();

Properties::table('users')->moveIn(['newsletter', 'locale' => 'ui.locale'])->run();
Schema::table('users', fn (Blueprint $table) => $table->dropColumn(['newsletter', 'locale']));

Properties::table('users')->moveOut(['ui.locale' => 'locale'])->run(); // the column must exist
sh
php artisan make:properties-migration users
sh
php artisan make:properties-migration users
php artisan make:properties-migration users --column=settings --jsonb --index=ui.theme
php artisan make:properties-migration users --encrypted