Nova Settings

repository·main·Indexed 43 days ago

https://github.com/outl1ne/nova-settings

A Laravel Nova package that allows developers to define custom settings using native Nova fields. It provides a dedicated UI for users to manage settings, supports data casting, subpage organization, and provides global helper functions like nova_get_setting() and nova_set_setting_value() for application-wide access.

Tokens
3.3K
Snippets
16
Records
20
Agent score
55%

What's inside Nova Settings

  1. Register the Nova Settings tool

    main

    To make the settings UI available in Laravel Nova, register the \Outl1ne\NovaSettings\NovaSettings class within the tools() method of your NovaServiceProvider.

    // in app/Providers/NovaServiceProvider.php
    
    public function tools()
    {
        return [
            // ...
            new \Outl1ne\NovaSettings\NovaSettings
        ];
    }
  2. Localize nova-settings

    main

    To translate the UI, publish the translation files:

    php artisan vendor:publish --provider="Outl1ne\NovaSettings\NovaSettingsServiceProvider" --tag="translations"

    Add your translations to resources/lang/vendor/nova-settings/ by creating a new locale file (e.g., et.json) based on the existing en.json.

  3. Configure nova-settings

    main

    Publish the configuration file to customize the package behavior:

    php artisan vendor:publish --provider="Outl1ne\NovaSettings\NovaSettingsServiceProvider" --tag="config"
    NameTypeDefaultDescription
    base_pathStringnova-settingsURL path of settings page.
    reload_page_on_saveBooleanfalseReload the entire page on save. Useful when updating any Nova UI related settings.
    models.settingsModelSettings::classOptionally override the Settings model.
    cacheString:memory:Cache store name to use. :memory: for singleton class, or null to turn off caching.
  4. How setting casts work in the Settings model

    main

    The Settings model automatically handles data casting based on the configuration provided by NovaSettings::getCasts().

    When you access the value attribute via $setting->value, the model checks if a cast is defined for that specific key. If a cast exists, the value is automatically transformed (e.g., to an array, boolean, or integer) before being returned.

    When setting a value via $setting->value = $newValue, the model checks the cast type. For datetime or date types, the value is stored as-is. For all other types, if the value is an array or implements JsonSerializable, it is automatically json_encoded before being stored in the database.

  5. Install and configure nova-settings

    main

    To use nova-settings, you need to publish the migrations and the configuration file to your application. This allows you to manage the database schema and customize the package behavior.

    Publish Migrations

    Run the following command to publish the database migrations to your database/migrations directory:

    php artisan vendor:publish --tag=migrations

    Publish Configuration

    Run the following command to publish the configuration file to your config directory:

    php artisan vendor:publish --tag=config
    php artisan vendor:publish --tag=migrations
    php artisan vendor:publish --tag=config
  6. Apply casts to settings values

    main

    To ensure settings are returned in a specific format (e.g., boolean, float, collection), pass an associative array as the second argument to addSettingsFields(). The keys should match your setting's database key.

    \Outl1ne\NovaSettings\NovaSettings::addSettingsFields([
        // ... fields
    ], [
      'some_boolean_value' => 'boolean',
      'some_float' => 'float',
      'some_collection' => 'collection',
      // ...
    ]);
  7. Organize settings into subpages

    main

    You can group settings into custom subpages by providing a subpage name as the third argument to addSettingsFields(). If omitted, settings appear under "General".

    To translate subpage names, publish the translations and add a key novaSettings.$subpage (where $subpage is the slugified, lowercase version of the name) to your translation files.

    \Outl1ne\NovaSettings\NovaSettings::addSettingsFields([
        Text::make('Some setting', 'some_setting'),
        Number::make('A number', 'a_number'),
    ], [], 'Subpage');
  8. Access settings with helper functions

    main

    Use the following global helper functions to interact with your settings in your application code:

    • nova_get_settings($keys = null, $defaults = []): Returns all settings as an array. If $keys is provided, returns only those keys. $defaults allows providing fallback values.
    • nova_get_setting($key, $default = null): Returns the value of a single setting. Returns $default if the key is not found.
    • nova_set_setting_value($key, $value = null): Programmatically sets a setting value.
  9. Register settings fields

    main

    Define your custom settings in the boot() method of your NovaServiceProvider using NovaSettings::addSettingsFields(). You can pass an array of Nova fields or a callable that returns an array. You can also use Panel::make() to group fields.

    // Using an array
    \Outl1ne\NovaSettings\NovaSettings::addSettingsFields([
        Text::make('Some setting', 'some_setting'),
        Number::make('A number', 'a_number'),
    ]);
    
    // OR
    
    // Using a callable
    \Outl1ne\NovaSettings\NovaSettings::addSettingsFields(function() {
      return [
        Text::make('Some setting', 'some_setting'),
        Number::make('A number', 'a_number'),
      ];
    });
    
    // Using a Panel
    \Outl1ne\NovaSettings\NovaSettings::addSettingsFields([
        Panel::make('Panel Title', [
          Text::make('Some setting', 'some_setting'),
          Number::make('A number', 'a_number'),
        ]),
    ]);
  10. Authorize settings visibility

    main

    You can control access to settings at two levels:

    1. Tool level: Hide the entire Settings tool from the Nova sidebar using canSee() on the tool instance.
    2. Field level: Hide specific settings fields using canSee() on the individual Nova field.
    // Hide the whole Settings area
    public function tools(): array
    {
        return [
            NovaSettings::make()->canSee(fn () => user()->isAdmin()),
        ];
    }
    
    // Hide specific fields
    Text::make('A text field')
      ->canSee(fn () => user()->isAdmin()),
  11. Customize the Nova Settings base path

    main

    You can change the URL path used to access the Nova Settings interface by modifying the base_path key in config/nova-settings.php. The default path is nova-settings.

    If you change this, the Inertia route will be updated to match your new base path.

    // config/nova-settings.php
    
    'base_path' => 'custom-settings-path',