App & Models Settings for Laravel

Overview

App & Models Settings for Laravel

Latest Version on Packagist GitHub Tests Action Status Total Downloads

This package allows you to store application wide and model specific Laravel settings. Settings values are type-cast and stored properly. You can also define your own casts and store repository.

Installation

Install the package via composer:

composer require smartisan/laravel-settings

Publish the config file with:

php artisan vendor:publish --provider="Smartisan\Settings\SettingsServiceProvider" --tag="config"

Publish the migration file with:

php artisan vendor:publish --provider="Smartisan\Settings\SettingsServiceProvider" --tag="migrations"

And finally run the migration with:

php artisan migrate

Usage

The package provides various APIs to access the settings manager. You can access it with Settings facade, settings() helper method and via HasSettings trait on your models.

Store Settings

You can set single entry, or multiple entries of settings. The values of objects will be cast according to the rules defined in settings.php config file.

  • One Entry
Settings::set('key', 'value');
  • Multiple Entries

You can set multiple settings entries by passing an associative array of keys and values. Casts will be applied on all the payload, even on nested arrays.

Settings::set([
    'k1' => Carbon::now(),
    'k2' => [
        'k3' => $user,
        'k4' => [
            'k5' => $model
        ],  
    ]
]);
  • Specify Settings Group

It's possible to categorize your settings into groups by calling group method.

Settings::group('name')->set('key', 'value');

Settings::group('name')->set([
    'k1' => 'v1',
    'k2' => 'v2',
]);
  • Model Specific Settings

It's also possible to set settings for a specific model by calling for method

Settings::for($model)->set('key', 'value');

Settings::for($model)->set([
    'k1' => 'v1',
    'k2' => 'v2',
]);
  • Mixing Filters

You can mix all filters together like this:

Settings::for($model)->group('name')->set('key', 'value');

Retrieve Settings

You can retrieve one or multiple entries and specify the default value if not exist.

  • One Entry
Settings::get('k1', 'default');
  • Multiple Entries

If the entry key does not exist, the default value will be placed instead

Settings::get(['k1', 'k2', 'k3'], 'default');
  • All Entries

If you want to retrieve all entries, you simply call all method. You can also specify the model or group. Also to excempt some specific keys.

Note: Remember that retrieving all entries without specifying the group or model, will retrieve all entries that has no group or model set. You can consider these as (global app settings).

Settings::all();

Settings::for($model)->all();

Settings::for($model)->group('name')->all();

Settings::except('k1', 'k2')->for($model)->group('name')->all();

Settings::except('k1')->for($model)->group('name')->all();

Forget Entry

You can remove entries by calling forget method.

Settings::forget('key');

Settings::for($model)->group('name')->forget('key');

Determine Existance

You can determine whether the given settings entry key exists or not

Settings::exist('key');

Settings::for($model)->exist('key');

Settings::for($model)->group('name')->exist('key');

Helper Method

The package also ships with a settings helper method, you can use it instead of using Settings Facade

settings()->set('key', 'value');
...

HasSettings Trait

You can use HasSettings trait on your Eloquent models as well

  1. First prepare your model
use Smartisan\Settings\HasSettings;

class User extends Model
{
    use HasSettings;    
}
  1. Now you can call settings() method on that model. This is equivelant to Settings::for($model)
$user->settings()->set('k1', 'v1');
...

Custom Repositories

If you don't want to use the database repository, you can easily create your own settings repository. To do that

  1. Create a class of your repository that implements Repository interface and implement the following methods
use Smartisan\Settings\Contracts\Repository;

class FileRepository implements Repository 
{
    public function get($key,$default = null) {
        //
    }
    
    public function set($key,$value = null) {
        //
    }
    
    public function forget($key) {
        //
    }
    
    public function all() {
        //
    }
}
  1. In settings configuration file, add your own repository config to repositories attribute
    'repositories' => [
        ...
        
        'file' => [
            ...
        ]
    ],
  1. Change the default repository in settings config file to your own repository implementation

Custom Casts

The package allows you to easily create your own casting rules of any object type.

  1. Create your own cast class that implements Castable interface.

Note: The set method is called when the value of the entries is being stored to the repository, and the get method is called when the value is being retrieved from the repository.

use Smartisan\Settings\Contracts\Castable;

class CustomCast implements Castable
{
    public function set($payload) {
        //
    }
    
    public function get($payload) {
        //
    }
}
  1. Add the casts to the array of casts in settings config file
'casts' => [
    ...
    CustomDataType::class => CustomCast::class
]

Note: If you want to pass a parameter to your cast, you can set an object of the cast instead of cast class name

'casts' => [
    ...
    CustomDataType::class => new CustomCast('param')
]

Settings Cache

You can easily enable or disable caching settings in settings.php config file. You can also specify which caching store to use

'cache' => [
    'enabled' => env('SETTINGS_CACHE_ENABLED', false),
    'store' => null,
    'prefix' => null,
],

Testing

To run the package's tests, simply call the following command

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Credits

Alternatives

License

The MIT License (MIT). Please see License File for more information.

You might also like...
Simple App Project

SimpleProject(CRUD) by Melvs Clone the repository with git clone Copy .env.example file to .env and edit database credentials there Run composer insta

Demo App for Symfony Twig & Live Components
Demo App for Symfony Twig & Live Components

Twig & Live Components Demo Hi there! You've stumbled across a treasure of demos for the the TwigComponent and LiveComponent libraries! Fun! If you wa

Symfony React Blank is a blank symfony and react project, use this template to start your app using Symfony as an backend api and React as a frontend library.

Symfony React Blank Symfony React Blank is a blank symfony and react project, use this template to start your app using Symfony as an backend api and

A Dashboard Panel for Shop Admins to control customers using Hyperstream App
A Dashboard Panel for Shop Admins to control customers using Hyperstream App

Overview 🪟 Hyperstream is an application that facilitates simple and easy self-service at supermarkets, eliminating long lines for customers and redu

🔪 WordPress + React Starter Kit: Spin up a WordPress-powered React app in one step
🔪 WordPress + React Starter Kit: Spin up a WordPress-powered React app in one step

Postlight's Headless WordPress + React Starter Kit is an automated toolset that will spin up three things: A WordPress backend that serves its data vi

Web-app that helps clinicians with interpreting ECG recordings

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

CodeIgniter 4 + Svelte App Starter

CodeIgniter4 + Svelte Application Starter 💡 Features: ⚡ Super fast single page application (SPA). 🔥 Hot Module Replacment (HMR). 🧩 Easy to install

CodeIgniter 4 + Vue3 App Starter

CodeIgniter 4 + Vue3 Application Starter Features: 💡 Super fast single page application (SPA). 🔥 Hot Module Replacment (HMR). 🧩 Easy to install and

A Laravel Starter Kit for Laravel. Built with Laravel 8.
A Laravel Starter Kit for Laravel. Built with Laravel 8.

Laravel Get Started Project Laravel Get Started Project is a basic crud app built with laravel 8. In this app a basic product crud created. Features i

Comments
  • Settings::all() method does not work as expected

    Settings::all() method does not work as expected

    Hi @iamohd

    |id|group|key|payload| |---|---|---|---| |1|title|null|{"$cast": null, "value": "Site Title"}| |2|description|null|{"$cast": null, "value": "Site Description"}| |3|email|null|{"$cast": null, "value": "[email protected]"}| |4|per_page|admin|{"$cast": null, "value": 10}|

    Settings::all();
    

    If this query works, you will see that records belonging to any group are excluded.

    I don't know why this behavior is exhibited. But there is a way to fix it with a little tap.

    vendor/smartisan/laravel-settings/src/Repositories/DatabaseRepository.php

    
    protected function getEntries($keys, $default)
    {
        ...
        return DB::connection($this->connection)
            ->table($this->table)
           ...
           // ->where('group', $group) // replace with below code
           ->when($group, function (Builder $builder) use ($group) {
               $builder->where('group', $group);
           })
          ...
    }
    

    It can now continue to work as expected.

    Also, Settings::paginate($perPage) wouldn't be bad at all.

    Thank you.

    opened by assoft 7
  •  Associative Arrays

    Associative Arrays

    Hi, a smal question. How do you check the setting if saved as an associative array. In the instance under, check the value of the K5 value. Settings::group('application')->get('k2.k4.k5', false); doesnt work.

    Settings::group('application')->set([
        'k1' => Carbon::now(),
        'k2' => [
            'k3' => $user,
            'k4' => [
                'k5' => true
            ],  
        ]
    ]);
    
    question 
    opened by webstudios1 1
  • Update DatabaseRepository.php

    Update DatabaseRepository.php

    The setting config('database.connection') does not exist. It only works because null is returned and then it uses the default connection. This should be changed to config('settings.repositories.database.connection').

    opened by daschws 0
Releases(2.0.0)
Owner
Mohammed Isa
Mohammed Isa
Identify app models with a URI. Inspired by the globalid gem.

Identify app models with a URI. Heavily inspired by the globalid gem. Global ID - Reference models by URI A Global ID is an app wide URI that uniquely

Tony Messias 31 Nov 18, 2022
An account management Panel based on Laravel7 framework. Include multiple payment, account management, system caching, admin notification, products models, and more.

ProxyPanel 简体中文 Support but not limited to: Shadowsocks,ShadowsocksR,ShadowsocksRR,V2Ray,Trojan,VNET Demo Demo will always on dev/latest code, rather

null 17 Sep 3, 2022
Quickly build an admin interface for your Eloquent models

Website | Documentation | Add-ons | Pricing | Services | Stack Overflow | Reddit | Blog | Newsletter Quickly build an admin interface for your Eloquen

Backpack for Laravel 2.5k Jan 6, 2023
An example of Laravel app that runs in a docker container with RoadRunner

This repository contains an example of Laravel (PHP Framework) application that runs in a docker container with RoadRunner (high-performance PHP appli

Paramtamtam 117 Dec 20, 2022
todolist app with vueJS frontend and laravel backend

todolist-vuejs-laravel A todolist app with vue.js frontend and laravel backend Demo demo Installation To run this locally, you'll need to clone the re

Isaac Kojo Yeboah 2 May 10, 2022
Simple web app with laravel build from scratch

Find Me Simple Web Application This "Find Me" matchmaking web-based application is useful for facilitating people who are looking for new relationship

Jieyab 15 Nov 26, 2022
Boilerplate for a standard tested resourceful Laravel app

Gold Standard A Laravel boilerplate resource This repo is an example of what I consider to be my "gold standard" of a resource-oritented application w

Dwight Watson 25 Mar 19, 2019
Laravel app boilerplate with email verification process on registration

The default master branch is for Laravel 5.4 , for Laravel 5.3 boilerplate switch to the v5.3 branch Laravel app boilerplate with email verification o

LUBUS 41 Jan 3, 2022
A CRUD app made with Laravel and VueJS 3 (API Composition)

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Ludovic Guénet 2 Apr 1, 2022