anlutro / laravel-settings Goto Github PK
View Code? Open in Web Editor NEWPersistent settings in Laravel
License: MIT License
Persistent settings in Laravel
License: MIT License
Hey Anlutro,
Thank you very much for your handy settings library.
I came accross a problem in the write() function of DatabaseSettingStore. The error occurs when I use setting keys with dot notation. In case such a setting item is updated, the current write method does not execute the update in line 96 but the insert in line 110. This is due the "isset IF condition" in line 95 that always returns false in case $data is a multi-dimensional array because the $key contains dot notation. Automatic resolution of a dot notation is apperently not supported by isset().
My suggested fix uses Laravels array_dot() function (see http://laravel.com/docs/4.2/helpers) to flatten the $data array in order to align the keys read from the database and those present in the $data array. The following write() function is working for me:
protected function write(array $data)
{
$keys = $this->newQuery()
->lists('key');
$updateData = array();
$dotData = array_dot($data);
foreach ($keys as $key) {
if (isset($dotData[$key])) {
$updateData[$key] = $dotData[$key];
unset($dotData[$key]);
}
}
foreach ($updateData as $key => $value) {
$this->newQuery()
->where('key', '=', $key)
->update(array('value' => $value));
}
if ($dotData) {
$dbData = $this->prepareWriteData($data);
$this->newQuery(true)
->insert($dbData);
}
}
If you agree to this solution, please commit a fix for it to your dev-master in packagist so that I can use it with Composer.
Thank you very much,
Jochen
Hi, could you perhaps add a bit more documentation on how to use the JSON store and the databse store, i guess that its something you change in the config, but an actual example would be nice
Just installed this on L5 and I get a settings file which looks like this: {}
when running your example code and an array that looks like this: Array()
I followed your setup instructions to the letter.
Hi, please could you update composer.json to allow installation with Laravel 5
I am trying to impliment this for an page that will allow the user in the admin section to set the colors.
The actual layout I have in settings.index.blade.php is:
<?php
@extends('layouts.admin')
@section('header')
<h2>
{!! link_to_route('admin.index','back',[],['class'=>'btn btn-default']) !!}
</h2>
@stop
@section('panel-heading')
<h3>Change you colors:</h3>
@stop
@section('content')
{!! Form::open(['route'=>['admin.settings.update',$settings], 'method'=>'PUT', 'class'=>'form']) !!}
<div class="form-group">
{!! Form::label('background_color','Background Color') !!}
{!! Form::text('background_color',Setting::get('background_color'),['class' => 'form-control'] ) !!}
</div>
<!-- Submit Button -->
<div class="form-group">
{!! Form::submit('Update',['class'=> 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
@stop ?>
The controller I have is:
public function index()
{
$settings = Settings::all();
return view('admin.settings.index')->with('settings',$settings);
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($settings)
{
echo $settings['background_color'];
Setting::set('background_color', '#000');
return redirect('admin');
}
The seed that I am using is:
<?php
class SettingsSeeder extends Seeder {
public function run()
{
DB::table('settings')->delete();
DB::table('settings')->insert([
[
'key' => 'background_color',
'value' => '#fff',
]
]);
}
} ?>
My goal is to have all settings in the view to be updated the site. What am I doing incorrectly? I'm able to get the #fff into admin view but I am unable to pass the new value into the controller to be updated in the setting. I tried using Setting::set('background_color', '#000');
. I would like to do this for all of the settings I have stored in the database. Any guidance would be great.
Hi,
Great package. Thanks.
I am unable to run the database migration. Throws an error at about here:
"message":"Call to undefined function config()"
I did a dirty little hack to bypass it. Very, very, very dirty I might add. Directly in the vendor files! Please check it out. Or maybe its just my box. I don't know. (Laravel 4.2, Package version: 0.4.2)
Hi,
I was wondering how would I go about using "nested.element".
Thanks
Every time I deploy my app I am unable to migrate my database because artisan throws an error saying the settings table does not exist.
It would be good if this automatically fell back to the JSON File Driver if the database table has not yet been created.
Related to #11 possibly? When using dot notation, or even passing an array, it is just inserting individual rows per setting. My code is as follows:
Setting::setExtraColumns(array(
'tenant_id' => $this->currentTenant->id
));
$settings = array(
'access_token' => $responseArray['access_token'],
'team_name' => $responseArray['team_name'],
'team_id' => $responseArray['team_id'],
'incoming_webhook_url' => $responseArray['incoming_webhook']['url'],
'incoming_webhook_configuration_url' => $responseArray['incoming_webhook']['url'],
'incoming_webhook_channel' => $responseArray['incoming_webhook']['channel'],
);
\Setting::set('slack', $settings);
\Setting::save();
This snippet inserts rows for each array value, with the key reading 'slack.access_token' for example
Hello! Thanks for this very nice package! I've tried others before non have been perfect, but this one it's really really close, I think it only needs a way to flush, clear or remove all saved settings. Right now I've made a function to loop over all settings and forget them one by one, but could be nice to have this function builtin.
Or maybe this already exists but is not in the docs. Searching in the source I haven't found it either.
Thanks!
"Persistent" is the correct spelling. "Persistant" is used in the package description, readme, etc.
After installing, when running:
$ php artisan config:publish anlutro/l4-settings
I get the following error:
PHP Fatal error: Class 'anlutro\LaravelSettings\ServiceProvider' not found in /path/to/my/app/vendor/laravel/framework/src/Illuminate/Foundat
ion/ProviderRepository.php on line 123
i make table columns just like in your readme: key, value, user_id
Can you please write me code for :
updating 5.2.31 gave me this error
Local.ERROR: Illuminate\Contracts\Container\BindingResolutionException: Target [anlutro\LaravelSettings\SettingStore] is not instantiable while building [anlutro\LaravelSettings\SettingsManager, anlutro\LaravelSettings\SaveMiddleware]. in /home/forge/staging.example.com/vendor/laravel/framework/src/Illuminate/Container/Container.php:752
Stack trace:
#0 /home/forge/staging.example.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(633): Illuminate\Container\Container->build('anlutro\\Laravel...', Array)
#1 /home/forge/staging.example.com/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(697): Illuminate\Container\Container->make('anlutro\\Laravel...', Array)
#2 /home/forge/staging.example.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(853): Illuminate\Foundation\Application->make('anlutro\\Laravel...')
#3 /home/forge/staging.example.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(808): Illuminate\Container\Container->resolveClass(Object(ReflectionParameter))
#4 /home/forge/staging.example.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(777): Illuminate\Container\Container->getDependencies(Array, Array)
#5 /home/forge/staging.example.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(633): Illuminate\Container\Container->build('anlutro\\Laravel...', Array)
#6 /home/forge/staging.example.com/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(697): Illuminate\Container\Container->make('anlutro\\Laravel...', Array)
#7 /home/forge/staging.example.com/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(152): Illuminate\Foundation\Application->make('anlutro\\Laravel...')
#8 /home/forge/staging.example.com/public/index.php(58): Illuminate\Foundation\Http\Kernel->terminate(Object(Illuminate\Http\Request), Object(Illuminate\Http\Response))
#9 {main}
See laravel/framework support for this
#laravel/framework/issues/13347
Hi Andreas,
Thank you for implementing this good idea, I'm trying to figure out the best way to preload the basic settings on the app, for example; Seeds. Have you suggestions?
Best!
Hi,
for JSON powered APIs the casts like Laravel 5 Eloquent property will be helpful.
add pls JSON_PRETTY_PRINT for JsonSettingStore:write(). This will be very helpfull, i gues :)
Hi,
I'm using this package in a Command, I need to read/update the settings everytime it runs.
I can read it just fine, but when I need to update the current setting it does nothing.
I'm using Laravel 5, the field I need to update is a date string with 'Y-m-d H:i:s' format.
If I use it in my controllers it works fine, it fails only in a custom command.
So one of my laravel 5.0.34 projects needs this utility. Installed it throw composer
composer require anlutro/l4-settings
// this adds 'anlutro/l4-settings": "^0.4.5' to composer.json
Added Service Provider & Facade
'providers' => [
.
.
'anlutro\LaravelSettings\ServiceProvider',
'aliases' => [
.
.
'Setting' => 'anlutro\LaravelSettings\Facade'
All exactly as always and according to README. But my controller goes throw FatalErrorException while trying to use 'Setting' facade.
use Illuminate\Http\Request;
use Artisan;
use Input;
class ConfigController extends Controller {
.
.
.
public function config(){
$server = Setting::get('server', 1); <<<<<<<< Class 'XXXXX\Http\Controllers\Setting' not found
$count = Setting::get('count', 1000);
return view('config')->with(compact('server','count'));
}
What can it be? Trully rare problem (maybe stupid, but rare)
Im getting the following error when running the config publish command.
php artisan config:publish anlutro/l4-settings
exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to undefined method Illuminate\Config\Repository::package()' in /Users/Thomas/Documents/OAD/Projects/Project/vendor/anlutro/l4-settings/src/ServiceProvider.php:57
Stack trace:
#0 /Users/Thomas/Documents/OAD/Projects/Project/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(116): Illuminate\Foundation\Bootstrap\HandleExceptions->fatalExceptionFromError(Array)
#1 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleShutdown()
#2 {main}
I've seen the extra coloumn example, but I'm not quite sure how i can work it into what I'm trying to do.
I want to use the package for system settings on a website, but i also want to have users settings in the same table/setup.
An example would be pricebands.
System default settings would be say
1, Value: 5 - Qty: 100
2, Value: 10 - Qty 200
3, Value: 20 - Qty 400
User settings would make this say:
1, Value: 5 - Qty: 100
2, Value: 7.5 - Qty 300
3, Value: 10 - Qty 600
Is this possible within this package or would we have to build something custom?
Many thanks
Thanks for your great package!
It would be nice if your package gave an option of saving array, object (after serialize()) to 1 key, like wordpress option.
Never mind, fixed :)
In ServiceProvider.php
, you're using $this->
while in a closure. That's a PHP 5.4 feature and breaks your compatibility with php 5.3.28 (Tested on One.com shared hosting). I've attached a pull request with the fix for this, which is passing it in as a use() variable instead.
Hi,
Is it possible to add a third option on the get method so it will return the default value on empty string also?
Trying to check if a setting exists or not, tried has and get, both yield the same illegal offset:
http://i.imgur.com/7PcTA3E.png
if(Setting::has('support.from_name')) echo 'a';
if(Setting::get('support.from_name')) echo 'a';
Trying to use extra-column, but having problems
[ErrorException]
call_user_func_array() expects parameter 1 to be a valid callback, class 'anlutro\LaravelSettings\JsonSettingStore' does not have a method 'setExtraColumns
although config/config/config.php has
'store' => 'database',
boot function of my provider is
\Setting::setExtraColumns(array('user_id' => \Session::get('userId')));
I believe databaseSettingStore should be loaded....not sure why this happening..
thanks for your help
Hi,
I have an issue with composer update and the error is
php artisan clear-compiled
{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Class 'anlutro\cURL\Laravel\cURLServiceProvider' not found","fil
e":"C:\wamp\www\xxxxxx\vendor\laravel\framework\src\Illuminate\Foundation\ProviderRepository.php","line":158}}Script php artis
an clear-compiled handling the post-update-cmd event returned with an error
What should I do with this error.
by the way. im using Laravel 4.2.17
Thanks!
When I try and call statically I get the error:
Non-static method anlutro\LaravelSettings\SettingStore::set() should not be called statically, assuming $this from incompatible context
This is what I'm trying:
use anlutro\LaravelSettings\DatabaseSettingStore as Setting;
Setting::set('foo', 'bar');
Setting::get('foo', 'default value');
Setting::save();
I can get this working but only by using the following:
use anlutro\LaravelSettings\DatabaseSettingStore as Setting;
$conn = DB::connection('database_connection');
$store = new Setting($conn,'settings');
$store->set('foo', 'bar');
$store->set('nest.one', 'nestone');
$store->set('nest.two', 'nesttwo');
$store->set('array', array('one', 'two'));
$store->save();
I'm a newbee to laravel so any help is really grateful
Hi,
Where should we call setExtraColumns and and custom Columns?
I'm getting FatalErrorException Class 'Setting' not found when using the Facade method
// app/config/app.php
'providers' => array(
...
'anlutro\LaravelSettings\ServiceProvider',
'aliases' => array(
....
'Settings' => 'anlutro\LaravelSettings\Facade',
Although type hinting in my controller, does work, using the Facade approach does not. The actual place where I want to use this package is in the before_save closure in a settings config file for FrozenNode's Administrator package, so I need to use the Facade method.
if ($this->has($key)) unset($this->data[$keys]);
Should be
if ($this->has($key)) unset($this->data[$key]);
\anlutro\l4-settings\src\SettingStore.php
/**
* Unset a key in the settings data.
*
* @param string $key
*/
public function forget($key)
{
if ($this->has($key)) unset($this->data[$keys]);
}
Store settings in memory only, and don't write them to anywhere permanent.
The use case for this is for Unit Tests. Can't be writing to a json file every time I run Unit Tests.
FatalErrorException in SaveMiddleware.php line 18: Interface 'Illuminate\Contracts\Routing\TerminableMiddleware' not found in SaveMiddleware.php line 18
I think class SaveMiddleware does not need to implement TerminableMiddleware interface anymore.
Is there any way to use laravel-settings with laravel-translatable (https://github.com/dimsav/laravel-translatable) ?
I need to store the value in a separate table for different languages (setting_translations) for example.
Hi Andreas
I'm using the db store method and I'm not able to get the 'forget' method to work. I've looked the source and I think the items that are forgotten are just removed from the array, so when the database queries are run there is nothing to remove any existing reference of that key in the database.
Hi, thank you for this amazing package.
I have 1 problem though. Even though I have setExtraColumns, I am not getting the correct value from setting for each user with Setting::all()
What could be the reason?
I'm using Cartalyst/Sentry for authentication. Thank you for your help.
I'm using Laravel 5.2 and trying to save settings by user.
I have created a service provider and into the boot method I have added the following lines:
\Setting::setExtraColumns(array(
'user_id' => auth()->user()->id
));
This service provider is stored in app/Providers/SettingsServiceProvider.php
and is added to the providers array in config/app.php file.
When I load the web site I get the following error:
ErrorException in SettingsServiceProvider.php line 11:
Trying to get property of non-object
So, I tried dd(auth()->user()) and this returns always null.
For authentication I use the Laravel authentication stuff.
If I call the setExtraColumns method in a controller that is using the settings then everything is OK.
What am I doing wrong?
Do you have plans to make laravel-settings compatible with laravel 4.2? The problem lies in your package dependency on "illuminate/support": "~4.1"
.
It would be cool to be able to get multiple settings like:
$settings = Setting::get(['finance.vat_rate', 'app_name']);
Return:
[
'finance' => [
'vat_rate' => 20,
],
'app_name' => 'My App'
]
In order to create an admin frontend to edit the database values, I have found problems with the nested array keys. In the end I added a helper function to flatten the array, maybe it could be nice to add it to the set of tools of the package:
function flatten($array, $prefix = '') {
$result = array();
foreach($array as $key=>$value) {
if(is_array($value)) {
$result = $result + flatten($value, $prefix . $key . '.');
}
else {
$result[$prefix . $key] = $value;
}
}
return $result;
}
So now I can just:
return view('admin.settings', [ 'settings' => Functions::flatten( \Setting::all() ) ]);
And in the view...
@foreach($settings as $key => $value)
<div class='form-group'>
{{ Form::label($key, ucwords(str_replace(".", " ", $key)), ['class' => 'col-sm-2 control-label']) }}
<div class="col-sm-10">
{{ Form::textarea($key, $value, ['class'=>'form-control', 'autofocus' => '']) }}
</div>
</div>
@endforeach
So, for this kind of data
It gives me a nice:
Just my 2 cents
if set provider with
anlutro\LaravelSettings\ServiceProvider
after command php artisan vendor:publish
i found message Fatal error: Uncaught Symfony\Component\Debug\Exception\FatalThrowableError: Undefined constant 'anlutro\LaravelSettings\ServiceProvider'
and i try with anlutro\LaravelSettings\ServiceProvider::class
okey. i can publish now.
say, my user has 10 different settings, should I add 10 more columns ( as example given in your repo)?
Is there any reason why this would be the case?
Got this error when running the migration for the settings table. Fixed by adding the following in the migration:
use Illuminate\Foundation\Application;
Hey,
I want to fetch settings for a user after the initial fetch is done for the current logged in user (in a route middleware). I have an email that has to be translated to the locale of the user which will receive it.
In the repo $this->loaded is set to true when the initial fetch is done, so the second time it skips this and returns the data.
Any hints or tips on how to conquer this problem?
php artisan migrate:refresh --seed
produces
Class 'CreateSettingsTable' not found
Hi, for some reason it wont save changes. Here is my code
use anlutro\LaravelSettings\SettingStore as Setting;
class SettingsRepository extends BaseRepository
{
function __construct( Setting $setting )
{
$this->setting = $setting;
}
public function findAll()
{
return $this->setting->all();
}
public function save()
{
$this->setting->save();
}
}
Hi anlutro and thank you for this nice package. I wanted to ask if in a future release it could be possible to have shared and individual settings. As far as I see you can only have one of the two at the moment.
With shared I mean settings, that are the same for everyone. If you change the name of the website in a CMS, it gets changed for everyone.
If you change the backend interface language you sometimes don't want other users to be affected.
Is this realizable?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.