Skip to content

Nobody9512/laravel-setting

 
 

Repository files navigation

Laravel Setting Package

Latest Version License PHP Version Laravel Version

A powerful and flexible Laravel package for managing application settings with database storage, caching support, and Artisan commands.

Features

  • 📦 Database Storage - Store settings in database with serialization support
  • 🚀 Caching - Built-in caching support for improved performance
  • 🎨 Multiple Data Types - Support for strings, integers, booleans, arrays, and objects
  • 🛠️ Artisan Commands - Manage settings via command line
  • 🧪 Fully Tested - Comprehensive test coverage
  • 🎯 Simple API - Easy-to-use static methods and helper functions
  • 🔧 Laravel Integration - Seamless integration with Laravel's service container

Table of Contents

Installation

Install the package via Composer:

composer require firdavs9512/laravel-setting

Publish Configuration and Migration

After installation, publish the configuration file and migration:

php artisan vendor:publish --provider="Firdavs9512\LaravelSetting\LaravelSettingServiceProvider"

Run the migration to create the settings table:

php artisan migrate

Configuration

The configuration file is located at config/laravel-setting.php:

return [
    // Cache configuration
    'cache' => [
        'enabled' => true,           // Enable/disable caching
        'store' => 'file',          // Cache store to use
        'expiration' => 3600,       // Cache expiration in seconds
    ],

    // Database table prefix
    'table_prefix' => 'laravel',   // Results in 'laravel_settings' table
];

Cache Configuration

  • enabled: Set to true to enable caching for better performance
  • store: Specify the cache store (file, redis, memcached, etc.)
  • expiration: Cache lifetime in seconds (default: 1 hour)

Basic Usage

Setting Values

use Firdavs9512\LaravelSetting\Setting;

// Set simple values
Setting::set('app.name', 'My Application');
Setting::set('app.version', '1.0.0');
Setting::set('app.debug', true);

// Set arrays
Setting::set('app.features', ['feature1', 'feature2', 'feature3']);

// Set objects
Setting::set('app.config', (object)['key' => 'value']);

Getting Values

// Get with default value
$name = Setting::get('app.name', 'Default App');

// Get without default (returns null if not found)
$version = Setting::get('app.version');

// Get array
$features = Setting::get('app.features', []);

Using Helper Function

// Get value
$name = setting('app.name', 'Default App');

// Set value
setting()->set('app.name', 'New Name');

// Check existence
$exists = setting()->has('app.name');

// Delete setting
setting()->delete('app.name');

API Reference

Core Methods

Setting::set(string $key, mixed $value): bool

Store a setting value in the database.

Setting::set('site.title', 'My Website');
Setting::set('site.options', ['option1', 'option2']);

Setting::get(string $key, mixed $default = null): mixed

Retrieve a setting value by key.

$title = Setting::get('site.title', 'Default Title');

Setting::has(string $key): bool

Check if a setting exists.

if (Setting::has('site.title')) {
    // Setting exists
}

Setting::delete(string $key): bool

Delete a setting by key.

Setting::delete('site.title');

Setting::forget(string $key): bool

Alias for delete() method.

Setting::forget('site.title');

Setting::all(): array

Get all settings as an associative array.

$allSettings = Setting::all();
// Returns: ['key1' => 'value1', 'key2' => 'value2', ...]

Setting::flush(): bool

Delete all settings from the database.

Setting::flush(); // Removes all settings

Setting::remember(string $key, callable $callback): mixed

Get a setting value or store the result of a callback if it doesn't exist.

$value = Setting::remember('expensive.calculation', function () {
    return performExpensiveCalculation();
});

Artisan Commands

The package provides several Artisan commands for managing settings via CLI:

Get a Setting

php artisan setting:get {key}

Example:

php artisan setting:get app.name
# Output: Setting 'app.name': My Application

Set a Setting

php artisan setting:set {key} {value} [--type=auto]

Available types: auto, string, int, bool, json, array

Examples:

# Auto-detect type
php artisan setting:set app.name "My App"

# Explicit integer
php artisan setting:set max.users 100 --type=int

# Boolean value
php artisan setting:set app.debug true --type=bool

# JSON/Array value
php artisan setting:set app.features '["feature1","feature2"]' --type=json

Delete a Setting

php artisan setting:delete {key} [--force]

Examples:

# With confirmation
php artisan setting:delete app.old_feature

# Without confirmation
php artisan setting:delete app.old_feature --force

List All Settings

php artisan setting:list [--filter=] [--json]

Examples:

# List all settings in table format
php artisan setting:list

# Filter by key pattern
php artisan setting:list --filter=app

# Output as JSON
php artisan setting:list --json

Flush All Settings

php artisan setting:flush [--force]

Examples:

# With confirmation
php artisan setting:flush

# Without confirmation (careful!)
php artisan setting:flush --force

Advanced Usage

Working with Complex Data

// Store user preferences
Setting::set('user.preferences', [
    'theme' => 'dark',
    'language' => 'en',
    'notifications' => [
        'email' => true,
        'push' => false,
    ]
]);

// Retrieve nested data
$preferences = Setting::get('user.preferences');
$theme = $preferences['theme'] ?? 'light';

Using with Laravel Config

You can integrate settings with Laravel's config system:

// In a service provider's boot method
public function boot()
{
    config(['app.name' => Setting::get('app.name', config('app.name'))]);
}

Caching Strategies

For frequently accessed settings:

// Use remember method for computed values
$value = Setting::remember('computed.value', function () {
    // Expensive operation
    return computeValue();
});

To manually clear cache:

// Clear specific setting cache
Cache::forget('laravel-setting-app.name');

// Or disable cache temporarily
config(['laravel-setting.cache.enabled' => false]);

Grouping Settings

Organize settings using dot notation:

// Email settings
Setting::set('mail.driver', 'smtp');
Setting::set('mail.host', 'smtp.example.com');
Setting::set('mail.port', 587);
Setting::set('mail.encryption', 'tls');

// Payment settings
Setting::set('payment.gateway', 'stripe');
Setting::set('payment.currency', 'USD');
Setting::set('payment.test_mode', true);

Testing

Running Tests

Run the test suite using PHPUnit:

# Run all tests
vendor/bin/phpunit

# Run with coverage
vendor/bin/phpunit --coverage-html coverage

# Run specific test suite
vendor/bin/phpunit --testsuite=Unit
vendor/bin/phpunit --testsuite=Feature

Writing Tests

When testing your application with this package:

use Firdavs9512\LaravelSetting\Setting;

class YourTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        // Clear settings before each test
        Setting::flush();
    }

    public function test_your_feature()
    {
        // Set up test settings
        Setting::set('test.key', 'test value');

        // Your test logic
        $this->assertEquals('test value', Setting::get('test.key'));
    }
}

Troubleshooting

Common Issues

Settings not persisting

  • Check database connection
  • Ensure migrations have been run
  • Verify table name matches configuration

Cache not updating

  • Clear application cache: php artisan cache:clear
  • Check cache configuration in config/laravel-setting.php
  • Verify cache driver is properly configured

Migration fails

  • Check if table already exists
  • Verify database user has CREATE TABLE permissions
  • Check table prefix configuration

Performance Tips

  1. Enable caching for production environments
  2. Use appropriate cache drivers (Redis/Memcached for high-traffic sites)
  3. Group related settings using dot notation
  4. Avoid storing large objects directly; consider using file storage with path references

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Changelog

Version 1.2.0

  • Added has(), delete(), all(), flush(), forget(), and remember() methods
  • Added comprehensive Artisan commands
  • Improved test coverage
  • Enhanced documentation

Version 1.1.1

  • Initial stable release
  • Basic get/set functionality
  • Cache support
  • Database storage

License

This package is open-source software licensed under the MIT license.

Credits

Support

For issues, questions, or suggestions, please open an issue on GitHub.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • PHP 100.0%