Laravel's configuration and localization systems allow developers to create dynamic, adaptable applications. By integrating database-driven site settings with Laravel’s config and localization features, you can make your app more customizable and user-friendly. This tutorial will guide you through dynamically setting app configurations (e.g., app name, description, timezone) and localization preferences (e.g., language) using site settings.
Scenario: Dynamic Config and Localization
Imagine an application where:
- Configurations like the app’s name, timezone, or default pagination limit are stored in the database.
- Localization adapts dynamically to user preferences or admin-defined site-wide language settings.
We’ll set up a system to:
- Retrieve these settings from the database.
- Dynamically update Laravel’s configuration and locale at runtime.
Step 1: Create a SiteSettings Table and Model
- Generate the Migration:
php artisan make:migration create_site_settings_table --create=site_settings
- Define the Schema:
In the migration file, add fields for app configuration and localization settings:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSiteSettingsTable extends Migration
{
public function up()
{
Schema::create('site_settings', function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->string('value')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('site_settings');
}
}
- Run the Migration:
php artisan migrate
- Create the Model:
Generate and define the SiteSetting model:
php artisan make:model SiteSetting
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SiteSetting extends Model
{
protected $fillable = ['key', 'value'];
}
Step 2: Seed the Database with Default Settings
Add initial settings for testing purposes.
- Create a Seeder:
php artisan make:seeder SiteSettingsSeeder
- Define Default Settings:
Open the seeder file and add default values:
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class SiteSettingsSeeder extends Seeder
{
public function run()
{
DB::table('site_settings')->insert([
['key' => 'app_name', 'value' => 'My Laravel App'],
['key' => 'app_timezone', 'value' => 'UTC'],
['key' => 'app_language', 'value' => 'en'],
]);
}
}
- Run the Seeder:
php artisan db:seed --class=SiteSettingsSeeder
Step 3: Dynamically Load Settings into Laravel Config
Use a service provider to load settings from the database and apply them to Laravel’s config system.
- Modify
AppServiceProvider:
Open App\Providers\AppServiceProvider.php and update the boot method:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\App;
use App\Models\SiteSetting;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
if (Schema::hasTable('site_settings')) {
$settings = SiteSetting::pluck('value', 'key');
// Set application name
Config::set('app.name', $settings['app_name'] ?? Config::get('app.name'));
// Set application timezone
Config::set('app.timezone', $settings['app_timezone'] ?? Config::get('app.timezone'));
// Set application language
App::setLocale($settings['app_language'] ?? Config::get('app.locale'));
}
}
}
- Why use
Config::setandApp::setLocale?
Config::set: Dynamically updates Laravel’s configuration values.App::setLocale: Sets the application’s locale for localization features.
Step 4: Use Localization in the Application
To use the dynamically set locale, ensure your app is ready for localization.
- Create Language Files:
Add language files in the resources/lang directory:
resources/lang/en/messages.php
resources/lang/es/messages.php
Example content for messages.php:
English (en/messages.php):
return [
'welcome' => 'Welcome to our application!',
];
Spanish (es/messages.php):
return [
'welcome' => '¡Bienvenido a nuestra aplicación!',
];
- Use Translations in Views:
Use the __('key') helper to access translations:
{{ __('messages.welcome') }}
- Test Dynamic Localization:
Update the app_language in the database (e.g., change it to es) and refresh your app to see the locale change.
Step 5: Admin Interface to Update Settings
Allow admins to manage settings dynamically via a web interface.
- Create a Controller:
php artisan make:controller Admin/SiteSettingsController
Define edit and update methods:
namespace App\Http\Controllers\Admin;
use App\Models\SiteSetting;
use Illuminate\Http\Request;
class SiteSettingsController extends Controller
{
public function edit()
{
$settings = SiteSetting::all();
return view('admin.settings.edit', compact('settings'));
}
public function update(Request $request)
{
foreach ($request->settings as $key => $value) {
SiteSetting::updateOrCreate(['key' => $key], ['value' => $value]);
}
return redirect()->back()->with('success', 'Settings updated successfully.');
}
}
- Create a Blade View:
Benefits of Dynamic Config and Localization
- Flexibility: Site settings are adjustable without changing code.
- Localization: Dynamically adapts the app’s language based on admin-defined settings.
- Customization: Configurations like app name, timezone, or language can be updated in real-time.
Conclusion
By combining Laravel’s config and localization systems with database-driven settings, you’ve built a dynamic and customizable foundation for your application. This approach is ideal for managing global settings and adapting your app’s behavior to user or admin preferences.