Settings API

Complete reference for the Settings API - storing, retrieving, updating, and deleting configuration values in LaraDashboard.

Settings API

LaraDashboard provides a simple key-value settings API for storing application configuration. Settings are stored in the database and can be accessed throughout your application.

Database Schema

Settings are stored in the settings table:

Column Type Description
id bigint Primary key
option_name string Unique setting key
option_value text Setting value (serialized if needed)
autoload boolean Load automatically on boot (default: false)
created_at timestamp Creation timestamp
updated_at timestamp Last update timestamp

Helper Functions

LaraDashboard provides global helper functions for working with settings.

add_setting()

Create or update a setting.

add_setting(string $optionName, mixed $optionValue, bool $autoload = false): void

Parameters:

  • $optionName - Unique setting key
  • $optionValue - Value to store (strings, numbers, arrays, objects)
  • $autoload - Whether to load on every request (default: false)

Examples:

// Simple string
add_setting('site_name', 'My Application');

// With autoload
add_setting('app_timezone', 'UTC', true);

// Array value (automatically serialized)
add_setting('allowed_file_types', ['jpg', 'png', 'pdf']);

// Boolean
add_setting('maintenance_mode', false);

// Numeric
add_setting('max_upload_size', 10485760);

get_setting()

Retrieve a setting value.

get_setting(string $optionName, mixed $default = null): mixed

Parameters:

  • $optionName - Setting key to retrieve
  • $default - Default value if setting doesn't exist

Examples:

// Get setting with default
$siteName = get_setting('site_name', 'Default Site');

// Get array setting
$fileTypes = get_setting('allowed_file_types', []);

// Get boolean
$maintenanceMode = get_setting('maintenance_mode', false);

// Check if enabled
if (get_setting('feature_enabled', false)) {
    // Feature is enabled
}

update_setting()

Update an existing setting.

update_setting(string $optionName, mixed $optionValue, ?bool $autoload = null): bool

Parameters:

  • $optionName - Setting key to update
  • $optionValue - New value
  • $autoload - Update autoload flag (null = keep current)

Returns: true if updated, false if setting doesn't exist

Examples:

// Update value only
update_setting('site_name', 'New Site Name');

// Update value and autoload
update_setting('cache_enabled', true, true);

// Check if update succeeded
if (update_setting('api_key', $newKey)) {
    // Updated successfully
} else {
    // Setting doesn't exist, use add_setting instead
    add_setting('api_key', $newKey);
}

delete_setting()

Remove a setting from the database.

delete_setting(string $optionName): bool

Parameters:

  • $optionName - Setting key to delete

Returns: true if deleted, false if not found

Examples:

// Delete a setting
delete_setting('deprecated_option');

// Conditional delete
if (delete_setting('temporary_token')) {
    Log::info('Token cleared');
}

get_settings()

Retrieve multiple settings.

get_settings(int|bool|null $autoload = true): array

Parameters:

  • $autoload - Filter by autoload status
    • true - Only autoloaded settings
    • false - Only non-autoloaded settings
    • -1 - All settings

Returns: Array of setting records

Examples:

// Get all autoloaded settings
$autoloaded = get_settings(true);

// Get all settings
$all = get_settings(-1);

// Process settings
foreach (get_settings(-1) as $setting) {
    echo $setting['option_name'] . ': ' . $setting['option_value'];
}

SettingService Class

For more control, use the SettingService directly:

use App\Services\SettingService;

$service = app(SettingService::class);

// Create/update
$setting = $service->addSetting('key', 'value', false);

// Read
$value = $service->getSetting('key');

// Update
$updated = $service->updateSetting('key', 'new-value');

// Delete
$deleted = $service->deleteSetting('key');

// Get all with search
$settings = $service->getAllSettings('search_term');

// Get by key (returns model)
$setting = $service->getSettingByKey('key');

Accessing via Config

Settings with autoload = true are available via Laravel's config:

// Access autoloaded settings
$siteName = config('settings.site_name');
$theme = config('settings.default_theme');

// In Blade
{{ config('settings.site_name') }}

How Autoload Works

  1. On application boot, all settings with autoload = true are loaded
  2. They're merged into Laravel's config under the settings key
  3. Access them like any config value: config('settings.key')
// Add an autoloaded setting
add_setting('app_tagline', 'Building the future', true);

// Later, access via config
echo config('settings.app_tagline'); // "Building the future"

Excluded Settings

Certain keys are automatically excluded from saving:

// Default excluded keys
$excluded = ['_token'];

// Add custom exclusions via hook
Hook::addFilter(CommonFilterHook::EXCLUDED_SETTING_KEYS, function ($keys) {
    return array_merge($keys, ['_method', 'submit']);
});

Action Hooks

The settings API fires action hooks for lifecycle events:

CRUD Hooks

use App\Enums\Hooks\SettingActionHook;
use App\Support\Facades\Hook;

// Before a setting is created
Hook::addAction(
    SettingActionHook::SETTING_CREATED_BEFORE,
    function (string $key, mixed $value) {
        Log::debug("Creating setting: {$key}");
    }
);

// After a setting is created
Hook::addAction(
    SettingActionHook::SETTING_CREATED_AFTER,
    function ($setting) {
        Cache::forget("setting:{$setting->option_name}");
    }
);

// Before update
Hook::addAction(
    SettingActionHook::SETTING_UPDATED_BEFORE,
    function ($setting, $newValue) {
        // Validate or transform value
    }
);

// After update
Hook::addAction(
    SettingActionHook::SETTING_UPDATED_AFTER,
    function ($setting, $oldValue) {
        Log::info("Setting {$setting->option_name} changed from {$oldValue}");
    }
);

// Before delete
Hook::addAction(
    SettingActionHook::SETTING_DELETED_BEFORE,
    function ($setting) {
        // Backup or validate
    }
);

// After delete
Hook::addAction(
    SettingActionHook::SETTING_DELETED_AFTER,
    function (string $key) {
        Cache::forget("setting:{$key}");
    }
);

Batch Save Hooks

// Before batch save (settings form submission)
Hook::addAction(
    SettingActionHook::SETTINGS_SAVING_BEFORE,
    function (array $settings) {
        Log::debug('Saving settings', $settings);
    }
);

// After batch save
Hook::addAction(
    SettingActionHook::SETTINGS_SAVED_AFTER,
    function (array $settings) {
        Cache::tags(['settings'])->flush();

        // Notify admin
        Notification::send(
            User::admins()->get(),
            new SettingsUpdatedNotification($settings)
        );
    }
);

Import/Export Hooks

// Before import
Hook::addAction(
    SettingActionHook::SETTINGS_IMPORTING_BEFORE,
    function (array $settings) {
        // Validate import data
    }
);

// After import
Hook::addAction(
    SettingActionHook::SETTINGS_IMPORTED_AFTER,
    function (array $settings) {
        Cache::flush();
    }
);

// Before export
Hook::addAction(
    SettingActionHook::SETTINGS_EXPORTING_BEFORE,
    function () {
        Log::info('Settings export started');
    }
);

// After export
Hook::addAction(
    SettingActionHook::SETTINGS_EXPORTED_AFTER,
    function (array $settings) {
        Log::info('Exported ' . count($settings) . ' settings');
    }
);

Cache Hooks

// Cache cleared
Hook::addAction(
    SettingActionHook::SETTINGS_CACHE_CLEARED,
    function () {
        Log::info('Settings cache cleared');
    }
);

// Cache refreshed
Hook::addAction(
    SettingActionHook::SETTINGS_CACHE_REFRESHED,
    function () {
        Log::info('Settings cache refreshed');
    }
);

Common Patterns

Module Settings with Defaults

<?php

namespace Modules\YourModule\Services;

class YourModuleSettingsService
{
    protected array $defaults = [
        'your_module_enabled' => true,
        'your_module_api_key' => '',
        'your_module_timeout' => 30,
        'your_module_options' => [],
    ];

    public function get(string $key, mixed $default = null): mixed
    {
        $fullKey = "your_module_{$key}";
        return get_setting($fullKey, $default ?? ($this->defaults[$fullKey] ?? null));
    }

    public function set(string $key, mixed $value): void
    {
        add_setting("your_module_{$key}", $value);
    }

    public function isEnabled(): bool
    {
        return (bool) $this->get('enabled', true);
    }

    public function getApiKey(): string
    {
        return (string) $this->get('api_key', '');
    }
}

Caching Settings

use Illuminate\Support\Facades\Cache;

// Cache expensive setting lookups
$value = Cache::remember('setting:complex_config', 3600, function () {
    return get_setting('complex_config', []);
});

// Clear cache when setting changes
Hook::addAction(
    SettingActionHook::SETTING_UPDATED_AFTER,
    function ($setting) {
        if ($setting->option_name === 'complex_config') {
            Cache::forget('setting:complex_config');
        }
    }
);

Validating Before Save

Hook::addFilter(
    SettingFilterHook::SETTINGS_UPDATE_VALIDATION_RULES,
    function (array $rules) {
        return array_merge($rules, [
            'your_module_api_key' => 'nullable|string|min:32',
            'your_module_timeout' => 'integer|min:1|max:300',
            'your_module_enabled' => 'boolean',
        ]);
    }
);

Setting Model

The Setting Eloquent model:

use App\Models\Setting;

// Query directly
$setting = Setting::where('option_name', 'site_name')->first();

// Create
Setting::create([
    'option_name' => 'new_setting',
    'option_value' => 'value',
    'autoload' => false,
]);

// Update
Setting::where('option_name', 'site_name')
    ->update(['option_value' => 'New Name']);

// Bulk operations
Setting::whereIn('option_name', ['key1', 'key2'])->delete();

Best Practices

  1. Use prefixes - your_module_ prevents conflicts
  2. Prefer helpers - Use get_setting() over direct queries
  3. Set autoload wisely - Only for frequently accessed settings
  4. Provide defaults - Always use default parameter
  5. Type cast - Cast to expected type: (bool) get_setting('enabled')
  6. Cache when needed - Cache complex or computed settings
  7. Use action hooks - For side effects like cache clearing
  8. Validate input - Add validation rules via filter hook

Quick Reference

Operation Helper Service Method
Create/Update add_setting($key, $value) addSetting($key, $value)
Read get_setting($key, $default) getSetting($key)
Update only update_setting($key, $value) updateSetting($key, $value)
Delete delete_setting($key) deleteSetting($key)
List all get_settings(-1) getSettings(-1)
Config access config('settings.key') -

Next Steps

/