Admin-Editable Settings Without Complex Code
Apps face a constant problem. Some settings belong in a .env file. Other settings must change via an admin panel without a new code deploy. Examples include site names, timezones, or registration settings.
Many developers store these in a database but create a mess. You end up with two ways to read data. One part of your app uses config() while another uses a database model. This leads to bugs where settings are inconsistent.
You can avoid this by using a single read path. Treat the database as a layer that overlays your config at boot.
Here is how to build it:
• Use a single source of truth. The database holds the value, but the application only reads via config(). • Use typed classes. Instead of loose arrays, use classes with strict types. This prevents typos and silent errors. • Load settings during the boot process. Use a service provider to pull database values and push them into the config array.
Watch out for these two technical traps:
The Timezone Trap Laravel sets the timezone early in the boot process. If you change the config value later, PHP still uses the old timezone. You must call date_default_timezone_set() manually to sync the global PHP setting with your new config value.
The Fresh Install Trap A new app has no database tables. If your boot process fails because the settings table is missing, the app won't start. You cannot run migrations if the app fails to boot. Wrap your settings logic in a try/catch block. This allows the app to fall back to .env defaults until you run your migrations.
Another tip for security: When disabling a feature like registration, do not just hide the button in the UI. Remove the feature from the config entirely. If you remove the feature from the config, the routes disappear. A hidden form with a live endpoint is a security risk. A missing route returns a 404.
Keep your code simple. Your controllers and views should not know if a setting came from a file or a database. They should only see config().
Source: https://dev.to/nasrulhazim/admin-editable-settings-without-giving-up-config-2cj0
