Building a Settings Feature in Laravel for Multi-Tenant Applications
This guide walks you through the process of building a settings feature in a Laravel application that
allows each tenant (or user) to customize features based on their needs. As an intermediate Laravel
user, you'll be introduced to best practices for database design, Eloquent relationships, and using
helpers to easily access settings throughout your application.
1. Database Design
Create a settings table with the following fields:
- id
- tenant_id (nullable for global settings)
- key
- value
- type (optional for casting)
You may use a migration:
Schema::create('settings', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('tenant_id')->nullable();
$table->string('key');
$table->text('value')->nullable();
$table->string('type')->nullable();
$table->timestamps();
});
2. Create a Setting Model
Run: php artisan make:model Setting
In the model, cast the value field appropriately:
protected \$casts = [
'value' => 'array', // or use json, integer, boolean as needed
];
3. Accessing Settings via Helper
Create a helper function:
function setting(\$key, \$default = null) {
\$tenantId = auth()->user()?->tenant_id;
\$setting = \App\Models\Setting::where('tenant_id', \$tenantId)->where('key', \$key)->first();
return \$setting?->value ?? \$default;
4. Saving Settings
To update or create a setting:
\App\Models\Setting::updateOrCreate(
['tenant_id' => \$tenantId, 'key' => \$key],
['value' => \$value]
);
5. UI for Settings
Create a form in Blade with key-value pairs.
Submit the form to a controller that handles creating/updating settings using updateOrCreate.
6. Advanced Tips
- Cache frequently used settings
- Use observers to trigger events when settings change
- Validate keys and types for security