A simple and flexible way to manage global or model-specific settings in your Laravel app.
- Define global settings
- Store settings in the database via Eloquent
- Cache settings for performance
- Attach settings to users or any other model
- Support for typed namespaced settings classes
Install the package via Composer:
composer require elegantly/laravel-settings
Publish the migration and run it:
php artisan vendor:publish --tag="settings-migrations"
php artisan migrate
Optionally, publish the configuration file:
php artisan vendor:publish --tag="settings-config"
Published config file (config/settings.php
):
use Elegantly\Settings\Models\Setting;
return [
/*
* The Eloquent model used to store and retrieve settings
*/
'model' => Setting::class,
/*
* Cache configuration for global settings
*/
'cache' => [
'enabled' => true,
'key' => 'settings',
'ttl' => 60 * 60 * 24, // 1 day
],
];
use Elegantly\Settings\Facades\Settings;
// Set a value
Settings::set(
namespace: 'home',
name: 'color',
value: 'white'
);
// Get a value
$setting = Settings::get(
namespace: 'home',
name: 'color'
);
$setting->value; // white
namespace App\Http\Controllers;
use Elegantly\Settings\Settings;
class UserController extends Controller
{
public function index(Settings $settings)
{
$settings->set(
namespace: 'home',
name: 'color',
value: 'white'
);
$setting = $settings->get(
namespace: 'home',
name: 'color'
);
$setting->value; // white
}
}
For better DX, define custom typed settings classes:
namespace App\Http\Controllers;
use App\Settings\HomeSettings;
class UserController extends Controller
{
public function index(HomeSettings $settings)
{
$settings->color; // white
$settings->color = 'black';
$settings->save();
}
}
namespace App\Settings;
use Elegantly\Settings\NamespacedSettings;
class HomeSettings extends NamespacedSettings
{
public ?string $color = null;
/** @var int[] */
public array $articles = [];
public static function getNamespace(): string
{
return 'home';
}
}
Run the test suite:
composer test
See CHANGELOG for details on recent changes.
See CONTRIBUTING for contribution guidelines.
Please review our security policy for reporting vulnerabilities.
This package is open-sourced under the MIT license.
Would you like a README badge for PHPStan or Laravel Pint added as well?