PHP code example of litepie / settings

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

    

litepie / settings example snippets


use Litepie\Settings\Facades\Settings;

// Set a global setting
Settings::set('app_name', 'My Application');

// Get a setting with default value
$appName = Settings::get('app_name', 'Default App');

// Set user-specific setting
Settings::set('theme', 'dark', $user);

// Get user setting with fallback to global
$theme = Settings::get('theme', 'light', $user);

// Check if setting exists
if (Settings::has('maintenance_mode')) {
    // Setting exists
}

// Delete a setting
Settings::forget('old_setting');

// Get setting with default
$value = settings('app_name', 'Default App');

// Get setting for specific owner
$userTheme = settings('theme', 'light', $user);

// Get the settings service instance
$settingsService = settings();

// Set setting using service
settings()->set('new_setting', 'value');

use Litepie\Settings\Traits\HasSettings;

class User extends Model
{
    use HasSettings;
}

class Company extends Model
{
    use HasSettings;
}

// Now you can use these methods:
$user->setSetting('preference', 'value');
$preference = $user->getSetting('preference', 'default');
$user->forgetSetting('old_preference');

// Get all settings for the user
$allSettings = $user->getAllSettings();

// Get settings by group
$notifications = $user->getSettingsByGroup('notifications');

// Set multiple settings at once
$user->setMultipleSettings([
    'theme' => 'dark',
    'language' => 'en',
    'timezone' => 'UTC'
]);

// String (default)
Settings::set('app_name', 'My App');

// Integer
Settings::set('max_users', 100, null, ['type' => 'integer']);

// Float/Decimal
Settings::set('tax_rate', 7.25, null, ['type' => 'float']);

// Boolean
Settings::set('maintenance_mode', false, null, ['type' => 'boolean']);

// Array
Settings::set('allowed_domains', ['example.com', 'test.com'], null, ['type' => 'array']);

// JSON (for complex objects)
Settings::set('api_config', ['key' => 'value', 'timeout' => 30], null, ['type' => 'json']);

// Encrypted (automatically encrypted/decrypted)
Settings::set('api_secret', 'secret-key', null, ['type' => 'encrypted']);

// File paths
Settings::set('logo_path', '/uploads/logo.png', null, ['type' => 'file']);

// Set setting with group and metadata
Settings::set('logo', 'logo.png', $company, [
    'group_id' => 1, // appearance group
    'description' => 'Company logo displayed in header',
    'type' => 'file',
    'is_public' => true,
    'validation_rules' => ['$groups = app(\Litepie\Settings\Models\SettingGroup::class)->active()->get();

// Set multiple settings at once
Settings::setMultiple([
    'site_name' => 'My Website',
    'site_description' => 'A great website',
    'contact_email' => '[email protected]',
    'max_upload_size' => 10485760, // 10MB
], $user);

// Get multiple settings with defaults
$settings = Settings::getMultiple([
    'site_name' => 'Default Site',
    'contact_email' => '[email protected]',
    'theme' => 'light'
], $user);

// Get all settings for an owner
$allUserSettings = Settings::all($user);
$allGlobalSettings = Settings::all(); // null = global

Settings::set('email_notifications', true, $user, [
    'type' => 'boolean',
    'depends_on' => ['notifications_enabled' => true]
]);

// This setting will only be available if notifications_enabled is true

// Clear specific setting cache
Settings::clearCache('app_name', $user);

// Clear all cache
Settings::clearCache();

// Temporarily disable caching
config(['settings.cache.enabled' => false]);
Settings::set('temp_setting', 'value');
config(['settings.cache.enabled' => true]);

'api' => [
    'prefix' => 'api/settings',
    'middleware' => ['auth:sanctum', 'throttle:60,1'],
    'rate_limit' => '60:1',
],


return [
    // Caching configuration
    'cache' => [
        'enabled' => true,
        'store' => env('SETTINGS_CACHE_STORE', 'default'),
        'prefix' => 'settings',
        'ttl' => 3600, // Cache time-to-live in seconds
    ],

    // Database settings
    'database' => [
        'table_prefix' => 'settings_',
        'connection' => env('SETTINGS_DB_CONNECTION', 'default'),
    ],

    // Security and encryption
    'encryption' => [
        'enabled' => true,
        'key' => env('SETTINGS_ENCRYPTION_KEY', env('APP_KEY')),
    ],

    // Data type mappings
    'types' => [
        'string' => \Litepie\Settings\Types\StringType::class,
        'integer' => \Litepie\Settings\Types\IntegerType::class,
        'float' => \Litepie\Settings\Types\FloatType::class,
        'boolean' => \Litepie\Settings\Types\BooleanType::class,
        'array' => \Litepie\Settings\Types\ArrayType::class,
        'json' => \Litepie\Settings\Types\JsonType::class,
        'file' => \Litepie\Settings\Types\FileType::class,
        'encrypted' => \Litepie\Settings\Types\EncryptedType::class,
    ],

    // Default setting groups
    'default_groups' => [
        'general' => 'General Settings',
        'appearance' => 'Appearance',
        'notifications' => 'Notifications',
        'security' => 'Security',
        'api' => 'API Configuration',
        'email' => 'Email Settings',
        'social' => 'Social Media',
    ],

    // Permission system
    'permissions' => [
        'view_settings' => 'View Settings',
        'edit_settings' => 'Edit Settings',
        'delete_settings' => 'Delete Settings',
        'manage_global_settings' => 'Manage Global Settings',
        'manage_company_settings' => 'Manage Company Settings',
        'export_settings' => 'Export Settings',
        'import_settings' => 'Import Settings',
    ],

    // API configuration
    'api' => [
        'prefix' => 'api/settings',
        'middleware' => ['auth:sanctum'],
        'rate_limit' => '60:1',
    ],

    // File upload settings
    'files' => [
        'disk' => 'public',
        'path' => 'settings',
        'max_size' => 2048, // KB
        'allowed_types' => ['jpg', 'jpeg', 'png', 'gif', 'pdf'],
    ],

    // Audit trail
    'audit' => [
        'enabled' => true,
        'keep_history_days' => 365,
    ],

    // Webhooks (optional)
    'webhooks' => [
        'enabled' => false,
        'endpoints' => [
            // 'setting.updated' => 'https://your-app.com/webhooks/settings'
        ],
    ],
];

use Litepie\Settings\Events\SettingCreated;
use Litepie\Settings\Events\SettingUpdated;
use Litepie\Settings\Events\SettingDeleted;

// Listen for setting events in EventServiceProvider
protected $listen = [
    SettingCreated::class => [
        YourSettingCreatedListener::class,
    ],
    SettingUpdated::class => [
        YourSettingUpdatedListener::class,
    ],
    SettingDeleted::class => [
        YourSettingDeletedListener::class,
    ],
];

// Listen for setting updates
Event::listen(SettingUpdated::class, function ($event) {
    $setting = $event->setting;
    $oldValue = $event->oldValue;
    $newValue = $event->newValue;
    
    // Log the change
    Log::info("Setting {$setting->key} changed from {$oldValue} to {$newValue}");
    
    // Send notification
    if ($setting->key === 'maintenance_mode') {
        // Notify administrators
    }
});

// Listen for setting creation
Event::listen(SettingCreated::class, function ($event) {
    $setting = $event->setting;
    
    // Initialize related data
    if ($setting->key === 'new_company') {
        // Setup default company settings
    }
});

// Get setting history
$setting = Settings::findByKey('app_name');
$history = $setting->history()->orderBy('created_at', 'desc')->get();

foreach ($history as $change) {
    echo "Changed from '{$change->old_value}' to '{$change->new_value}' ";
    echo "by {$change->changedBy->name} ";
    echo "on {$change->created_at->format('Y-m-d H:i:s')}";
}

// Get recent changes
$recentChanges = app(\Litepie\Settings\Models\SettingHistory::class)
    ->with(['setting', 'changedBy'])
    ->latest()
    ->limit(10)
    ->get();

'audit' => [
    'enabled' => true,
    'keep_history_days' => 365, // Keep history for 1 year
],

// Set encrypted setting
Settings::set('api_secret', 'secret-value', null, ['type' => 'encrypted']);

// Value is automatically encrypted in database
// and decrypted when retrieved
$secret = Settings::get('api_secret'); // Returns 'secret-value'

// Check permissions before setting operations
if (auth()->user()->can('manage_global_settings')) {
    Settings::set('global_setting', 'value');
}

// Available permissions
$permissions = [
    'view_settings',
    'edit_settings', 
    'delete_settings',
    'manage_global_settings',
    'manage_company_settings',
    'export_settings',
    'import_settings'
];

// Public setting (can be accessed via API without authentication)
Settings::set('app_version', '1.0.0', null, [
    'is_public' => true,
    'description' => 'Current application version'
]);

// Private setting (

Settings::set('max_file_size', 10240, null, [
    'type' => 'integer',
    'validation_rules' => ['integer', 'min:1024', 'max:104857600'], // 1KB to 100MB
    'description' => 'Maximum file upload size in bytes'
]);

Settings::set('contact_email', '[email protected]', null, [
    'validation_rules' => ['email', '

// Company-specific settings
class Company extends Model 
{
    use HasSettings;
}

$company = Company::find(1);

// Set company branding
$company->setMultipleSettings([
    'company_name' => 'Acme Corp',
    'logo_url' => '/storage/logos/acme.png',
    'primary_color' => '#007bff',
    'secondary_color' => '#6c757d',
    'timezone' => 'America/New_York',
    'date_format' => 'Y-m-d',
    'currency' => 'USD'
]);

// User inherits company settings but can override
$user = User::find(1);
$user->setSetting('timezone', 'America/Los_Angeles'); // Override company timezone
$user->setSetting('theme', 'dark'); // Personal preference

// Getting settings with fallback hierarchy
$timezone = $user->getSetting('timezone'); // Returns 'America/Los_Angeles'
$currency = $user->getSetting('currency'); // Falls back to company setting 'USD'

// Store settings with groups
$store = Store::find(1);

// Payment settings
$store->setMultipleSettings([
    'stripe_public_key' => 'pk_test_...',
    'stripe_secret_key' => 'sk_test_...',
    'paypal_client_id' => 'your_paypal_client_id',
    'payment_methods' => ['stripe', 'paypal', 'bank_transfer']
], ['group_id' => 'payment']);

// Shipping settings  
$store->setMultipleSettings([
    'free_shipping_threshold' => 50.00,
    'shipping_zones' => ['domestic', 'international'],
    'default_shipping_method' => 'standard'
], ['group_id' => 'shipping']);

// Tax settings
$store->setMultipleSettings([
    'tax_enabled' => true,
    'tax_rate' => 8.25,
    'tax_inclusive' => false
], ['group_id' => 'tax']);

// Global application settings
Settings::setMultiple([
    'app_name' => 'SaaS Platform',
    'app_version' => '2.1.0',
    'maintenance_mode' => false,
    'max_users_per_account' => 100,
    'feature_flags' => [
        'new_dashboard' => true,
        'advanced_analytics' => false,
        'api_v2' => true
    ]
]);

// Account-specific limits
$account = Account::find(1);
$account->setMultipleSettings([
    'plan_type' => 'premium',
    'max_projects' => 50,
    'api_rate_limit' => 1000,
    'storage_limit' => 107374182400, // 100GB in bytes
    'custom_domain_enabled' => true
]);

// Check feature availability
if ($account->getSetting('custom_domain_enabled', false)) {
    // Allow custom domain setup
}

// Example hierarchy
$globalTheme = Settings::get('theme'); // 'light' (global default)
$companyTheme = Settings::get('theme', null, $company); // 'corporate' (company override)
$userTheme = Settings::get('theme', null, $user); // 'dark' (user preference)

// The user gets 'dark', company users without preference get 'corporate'

// Use bulk operations for better performance
Settings::setMultiple([
    'setting1' => 'value1',
    'setting2' => 'value2',
    'setting3' => 'value3'
], $user);

// Instead of:
Settings::set('setting1', 'value1', $user);
Settings::set('setting2', 'value2', $user);
Settings::set('setting3', 'value3', $user);

// Preload settings to avoid N+1 queries
$users = User::with('settings')->get();
foreach ($users as $user) {
    $theme = $user->getSetting('theme'); // No additional query
}

// Use dot notation for nested settings
Settings::set('email.smtp.host', 'smtp.gmail.com');
Settings::set('email.smtp.port', 587);
Settings::set('email.smtp.encryption', 'tls');

// Use descriptive names
Settings::set('max_upload_file_size', 10485760); // Good
Settings::set('max_size', 10485760); // Too vague

// Group related settings
Settings::set('notification.email.enabled', true);
Settings::set('notification.sms.enabled', false);
Settings::set('notification.push.enabled', true);

use Litepie\Settings\Exceptions\SettingNotFoundException;
use Litepie\Settings\Exceptions\InvalidSettingTypeException;

try {
    Settings::set('invalid_type_setting', 'value', null, ['type' => 'unknown']);
} catch (InvalidSettingTypeException $e) {
    // Handle invalid type
    Log::error('Invalid setting type: ' . $e->getMessage());
}

// Safe getting with defaults
$criticalSetting = Settings::get('critical_setting', 'safe_default');

// Check existence before operations
if (Settings::has('feature_flag')) {
    $enabled = Settings::get('feature_flag');
}



namespace App\Settings\Types;

class ColorType
{
    public static function cast($value)
    {
        // Ensure value is a valid hex color
        if (!preg_match('/^#[a-f0-9]{6}$/i', $value)) {
            return '#000000'; // Default to black
        }
        return $value;
    }

    public static function serialize($value)
    {
        return self::cast($value);
    }

    public static function validate($value, $rules = [])
    {
        return preg_match('/^#[a-f0-9]{6}$/i', $value);
    }
}

'types' => [
    // ... existing types
    'color' => \App\Settings\Types\ColorType::class,
],

Settings::set('brand_color', '#007bff', null, ['type' => 'color']);
$color = Settings::get('brand_color'); // Always returns valid hex color

// Clear all settings cache
Settings::clearCache();

// Or use artisan command
php artisan settings:cache:clear

// Check cache configuration
php artisan config:cache

// Check database connection
php artisan migrate:status

// Verify table exists
Schema::hasTable('settings_settings');

// Check for validation errors
try {
    Settings::set('test', 'value');
} catch (\Exception $e) {
    Log::error('Setting error: ' . $e->getMessage());
}

// Enable query logging to identify N+1 queries
DB::enableQueryLog();
$settings = Settings::all($user);
$queries = DB::getQueryLog();

// Check cache hit ratio
$cacheKey = 'settings:global:app_name';
$hit = Cache::has($cacheKey);

// Check user permissions
if (!auth()->user()->can('edit_settings')) {
    abort(403, 'Permission denied');
}

// Verify middleware configuration
'middleware' => ['auth:sanctum', 'can:manage_settings'],

'debug' => env('SETTINGS_DEBUG', false),



namespace Tests\Feature;

use Tests\TestCase;
use Litepie\Settings\Facades\Settings;
use Illuminate\Foundation\Testing\RefreshDatabase;

class SettingsTest extends TestCase
{
    use RefreshDatabase;

    public function test_can_set_and_get_setting()
    {
        Settings::set('test_setting', 'test_value');
        
        $this->assertEquals('test_value', Settings::get('test_setting'));
    }

    public function test_user_settings_override_global()
    {
        $user = User::factory()->create();
        
        Settings::set('theme', 'light'); // Global
        Settings::set('theme', 'dark', $user); // User-specific
        
        $this->assertEquals('light', Settings::get('theme'));
        $this->assertEquals('dark', Settings::get('theme', null, $user));
    }

    public function test_settings_are_cached()
    {
        Settings::set('cached_setting', 'value');
        
        // First call hits database
        $value1 = Settings::get('cached_setting');
        
        // Second call hits cache
        $value2 = Settings::get('cached_setting');
        
        $this->assertEquals($value1, $value2);
    }
}

// Mock the settings service
$mock = Mockery::mock(SettingsService::class);
$mock->shouldReceive('get')
     ->with('test_setting')
     ->andReturn('mocked_value');

$this->app->instance('settings', $mock);

// Use settings normally in your test
$value = Settings::get('test_setting'); // Returns 'mocked_value'

// Old way (spatie)
use Spatie\LaravelSettings\Settings as SpatieSettings;

class GeneralSettings extends SpatieSettings
{
    public string $site_name;
    public bool $site_active;
    
    public static function group(): string
    {
        return 'general';
    }
}

// New way (Litepie)
Settings::setMultiple([
    'site_name' => 'My Site',
    'site_active' => true
], null, ['group_id' => 'general']);

// Old way (anlutro)
use anlutro\LaravelSettings\Facade as SettingsFacade;

SettingsFacade::set('key', 'value');
$value = SettingsFacade::get('key');

// New way (Litepie) - mostly compatible
use Litepie\Settings\Facades\Settings;

Settings::set('key', 'value');
$value = Settings::get('key');



use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

class MigrateFromOldSettingsPackage extends Migration
{
    public function up()
    {
        // Example: Migrate from simple key-value table
        $oldSettings = DB::table('old_settings')->get();
        
        foreach ($oldSettings as $setting) {
            DB::table('settings_settings')->insert([
                'key' => $setting->key,
                'value' => $setting->value,
                'type' => 'string', // Assume string type
                'owner_type' => null,
                'owner_id' => null,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }
}
bash
# Install the package (publishes config, runs migrations, seeds default groups)
php artisan settings:install

# Or run steps manually:
php artisan vendor:publish --provider="Litepie\Settings\Providers\SettingsServiceProvider"
php artisan migrate
php artisan settings:seed
bash
php artisan vendor:publish --provider="Litepie\Settings\Providers\SettingsServiceProvider" --tag="settings-config"
bash
# Complete package installation (recommended)
php artisan settings:install

# Seed default setting groups
php artisan settings:seed
bash
php artisan vendor:publish --provider="Litepie\Settings\Providers\SettingsServiceProvider" --tag="settings-config"