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'
]);
// 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
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 (
// 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);
}
}
// 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