|
| 1 | +--- |
| 2 | +title: Settings |
| 3 | +order: 450 |
| 4 | +--- |
| 5 | + |
| 6 | +## Storing Settings |
| 7 | + |
| 8 | +NativePHP offers an easy method to store and retrieve settings in your application. This is helpful for saving application-wide |
| 9 | +settings that persist even after closing and reopening the application. |
| 10 | + |
| 11 | +Settings are managed using the `Settings` facade and are stored in a file named `config.json` in the |
| 12 | +[`appdata`](/docs/getting-started/debugging#start-from-scratch) directory of your application. |
| 13 | + |
| 14 | +```php |
| 15 | +use Native\Laravel\Facades\Settings; |
| 16 | +``` |
| 17 | + |
| 18 | +### Setting a value |
| 19 | +It's as simple as calling the `set` method. The key must be a string. |
| 20 | +```php |
| 21 | +Settings::set('key', 'value'); |
| 22 | +``` |
| 23 | + |
| 24 | +### Getting a value |
| 25 | +To retrieve a setting, use the `get` method. |
| 26 | +```php |
| 27 | +$value = Settings::get('key'); |
| 28 | +``` |
| 29 | + |
| 30 | +You may also provide a default value to return if the setting does not exist. |
| 31 | +```php |
| 32 | +$value = Settings::get('key', 'default'); |
| 33 | +``` |
| 34 | +If the setting does not exist, `default` will be returned. |
| 35 | + |
| 36 | +### Forgetting a value |
| 37 | +If you want to remove a setting altogether, use the `forget` method. |
| 38 | +```php |
| 39 | +Settings::forget('key'); |
| 40 | +``` |
| 41 | + |
| 42 | +### Clearing all settings |
| 43 | +To remove all settings, use the `clear` method. |
| 44 | +```php |
| 45 | +Settings::clear(); |
| 46 | +``` |
| 47 | +This will remove all settings from the `config.json` file. |
| 48 | + |
| 49 | +## Events |
| 50 | + |
| 51 | +### `SettingChanged` |
| 52 | +The `Native\Laravel\Events\Notifications\SettingChanged` event is dispatched when a setting is changed. |
| 53 | + |
| 54 | +Example usage: |
| 55 | +```php |
| 56 | +Event::listen(SettingChanged::class, function (SettingChanged $event) { |
| 57 | + $key = $event->key; // Key of the setting that was changed |
| 58 | + $value = $event->value; // New value of the setting |
| 59 | +}); |
| 60 | +``` |
| 61 | + |
| 62 | +This event can also be listened with Livewire to refresh your settings page: |
| 63 | +```php |
| 64 | +use Livewire\Component; |
| 65 | +use Native\Laravel\Events\Notifications\SettingChanged; |
| 66 | + |
| 67 | +class Settings extends Component |
| 68 | +{ |
| 69 | + protected $listeners = [ |
| 70 | + 'native:'.SettingChanged::class => '$refresh', |
| 71 | + ]; |
| 72 | +} |
| 73 | +``` |
| 74 | + |
0 commit comments