This Laravel package provides a complete configuration solution ready to be integrated into your application.
- NoSQL-like Flexibility: Add schema-less dynamic attributes to any Eloquent model without database migrations
- Type-Safe Storage: Supports strings, integers, arrays, JSON, dates with automatic type casting via
ConfigValueTypeenum - Polymorphic Relationships: Any model can have configurations through a single, flexible relationship
- Ready-to-use endpoints: Complete API for managing configurations
- OpenAPI documentation: Automatically generated documentation using PHP attributes
- Configuration file: Easily customize settings
- Laravel agnostic considerations: designed with future framework agnosticism in mind
This package includes a Docker development environment and Makefile for easy development.
# Start the development environment
make up
# Install dependencies
make install
# Run tests
make test
# Run code formatter
make pint
# Show all available commands
make helpmake up- Start Docker containersmake down- Stop Docker containersmake install- Install dependenciesmake test- Run testsmake pint- Run Laravel Pint code formattermake lint- Alias for pintmake fresh- Fresh start (down, up, install)make setup- Complete setup with testsmake check- Run all checks (formatting + tests)make shell- Access container shell
composer require whilesmart/eloquent-model-configurationYou do not need to publish the migrations and configurations except if you want to make modifications. You can choose to publish the migrations, routes, controllers separately or all at once.
Run the command below to publish only the routes.
php artisan vendor:publish --tag=model-configuration-routes
php artisan migrateThe routes will be available at routes/model-configuration.php. You should require this file in your api.php file.
require 'model-configuration.php';+If you would like to make changes to the migration files, run the command below to publish only the migrations.
php artisan vendor:publish --tag=model-configuration-migrations
php artisan migrateThe migrations will be available in the database/migrations folder.
By default the controllers assign the device to the currently logged in user. If you would like to assign the device to
another model, you can publish the controllers and make the necessary changes to the published file.
To publish the controllers, run the command below
php artisan vendor:publish --tag=model-configuration-controllers
php artisan migrateThe controllers will be available in the app/Http/Controllers directory.
Finally, change the namespace in the published controllers to your namespace.
To publish the openapi documentation, run the command below
php artisan vendor:publish --tag=model-configuration-docsThe documentation will be available at app/Http/Documentation
To publish the migrations, routes and controllers, you can run the command below
php artisan vendor:publish --tag=model-configuration
php artisan migrateThe default controller gets the authenticated user from the Request object. The default routes must be placed in an auth middleware. Set your auth middleware in the config/model-configuration.php file.
<?php
return [
...,
'auth_middleware' => ['auth:sanctum'],
];Config keys are case-insensitive by default. For example ConfigName and configname are considered the same. To change this behavior, set the allow_case_insensitive_keys config variable to true.
<?php
return [
...,
'allow_case_insensitive_keys' => true,
];Config names can take only the following:
- Lowercase characters: a to z
- Uppercase characters: A to Z
- Numbers: 0 to 9
- Some special characters: hyphen (-), underscore (_), fullstop (.) and plus (+)
You can also restrict the key names allowed by adding each allowed key name in the allowed_keys array
<?php
return [
...,
'allowed_keys' => ['key-1','key-2'],
];You can also define Laravel validation rules for each key's value:
<?php
return [
...,
'allowed_keys' => [
'max_items' => 'integer|min:1|max:100',
'site_name' => 'string|max:50',
'simple_key', // No validation rules
],
];If you need to extend the Configuration model with additional functionality (e.g., soft deletes, auditing, or custom traits), you can use your own model class:
Step 1: Create a custom model that extends the base Configuration model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Whilesmart\ModelConfiguration\Models\Configuration as BaseConfiguration;
class Configuration extends BaseConfiguration
{
use SoftDeletes;
protected $fillable = ['configurable_id', 'configurable_type', 'key', 'type', 'value', 'metadata'];
}Step 2: Configure the package to use your custom model:
<?php
return [
...,
'model' => \App\Models\Configuration::class,
];Step 3: Use the package normally - no need to override traits or controllers!
The package will automatically use your custom model for all configuration operations. This allows you to:
- Add Laravel traits (SoftDeletes, Auditable, etc.)
- Include additional attributes and relationships
- Implement custom business logic at the model level
- Receive automatic package updates without maintaining custom controllers
Register hooks to customize behavior. A single hook class can implement one or both interfaces:
<?php
return [
...,
'hooks' => [
PaginateResultsHook::class,
OnboardingCompletedHook::class,
],
];Runs before/after HTTP requests to configuration endpoints.
class PaginateResultsHook implements ModelHookInterface
{
public function beforeQuery(mixed $data, ConfigAction $action, Request $request): mixed
{
if ($action == ConfigAction::INDEX) {
return $data->paginate();
}
return $data;
}
public function afterQuery(mixed $results, ConfigAction $action, Request $request): mixed
{
return $results;
}
}Runs when setConfigValue() is called, useful for triggering side effects.
use Illuminate\Database\Eloquent\Model;
use Whilesmart\ModelConfiguration\Enums\ConfigValueType;
use Whilesmart\ModelConfiguration\Interfaces\ConfigValueHookInterface;
use Whilesmart\ModelConfiguration\Models\Configuration;
class OnboardingCompletedHook implements ConfigValueHookInterface
{
public function onConfigValueSet(
Model $model,
string $key,
mixed $value,
ConfigValueType $type,
Configuration $configuration,
bool $wasCreated
): void {
if ($key === 'onboarding_completed' && $value === 'true') {
app(OnboardingService::class)->complete($model);
}
}
}The hook receives:
$model- The model that owns the configuration (e.g., User)$key- The configuration key that was set$value- The new value$type- The ConfigValueType enum$configuration- The Configuration model instance$wasCreated-trueif this was a new configuration,falseif updated
A single class can implement both interfaces:
class MyHook implements ModelHookInterface, ConfigValueHookInterface
{
public function beforeQuery(mixed $data, ConfigAction $action, Request $request): mixed
{
return $data;
}
public function afterQuery(mixed $results, ConfigAction $action, Request $request): mixed
{
return $results;
}
public function onConfigValueSet(
Model $model,
string $key,
mixed $value,
ConfigValueType $type,
Configuration $configuration,
bool $wasCreated
): void {
// Handle value changes
}
}
### 3. Model Relationships
We have implemented a Trait `Configurable` that handles relationships. If your model has configuration, simply use the
`Configurable` trait in your model definition.
```php
use Whilesmart\ModelConfiguration\Traits\Configurable
class MyModel {
use Configurable;
}
You can call yourModel->configurations() to get the list of configuration tied to the model
$model = new MyModel();
$model->configurations();The Configurable trait also has the getConfigurationssAttribute() method. If you want to append the configuration to the model response, simply add configuration to your model's $appends
use Whilesmart\ModelConfiguration\Traits\Configurable;
class MyModel {
use Configurable;
protected $appends = ['configurations'];
}The following additional methods are available also available in the Configurable trait
getConfig()gets the full details of a particular config. It returns aConfigurationobject
$model = new MyModel();
$config = $model->getConfig('default_wallet');
$config_id = $config->id;getConfigValue()gets the value of a particular config. It also ensures the value is returned in the correct type
$model = new MyModel();
$config_value = $model->getConfigValue('default_wallet');getConfigType()gets the type of a particular config. It returns aConfigValueTypeenum
$model = new MyModel();
$config_type = $model->getConfigType('default_wallet');setConfigValue()sets/updates the value of a particular config. It returns aConfigurationobject
$model = new MyModel();
$config= $model->setConfigValue('default_wallet',1, ConfigValueType::Integer);After installation, the following API endpoints will be available:
- POST /api/configurations: Registers a new config linked to the current logged in user.
- GET /api/configurations: Retrieves all configurations linked to the current logged in user.
- PUT /api/configurations/{id}: Updates the information in a configuration.
- DELETE /api/configurations/{id}: Deletes a configuration.
- OpenAPI Documentation: Accessible via a route that your OpenAPI package defines.
Example Request:
{
"value":"unique_token_string",
"type":"string"
}