Laravel - set a global variable from the settings table

I am trying to save all my settings from the settings table to a global variable, but now I'm stuck (I don't know what the next step is), this is my actual model and seeder:

model - Settings.php

 class Setting extends Model { protected $table = 'settings'; public $timestamps = false; protected $fillable = [ 'name', 'value', ]; } 

seeder - SettingsTableSeeder.php

 class SettingsTableSeeder extends Seeder { public function run() { $settings = [ ['name' => 'title', 'value' => ''], ['name' => 'facebook', 'value' => ''], ['name' => 'twitter', 'value' => ''], ['name' => 'instagram', 'value' => ''] ]; foreach($settings as $setting){ \App\Setting::create($setting); } } } 

How can I store all the data in the settings table and make it accessible from the blade or any controller or view?

Edit


Now, my question is: how can I update one or more values ​​from a form?

I installed this:

My route:

 Route::put('/', ['as' => 'setting.update', 'uses' => 'Admin\ AdminConfiguracoesController@update ']); 

My Admin \ AdminConfiguracoesController:

 class AdminConfiguracoesController extends AdminBaseController { private $repository; public function __construct(SettingRepository $repository){ $this->repository = $repository; } public function geral() { return view('admin.pages.admin.configuracoes.geral.index'); } public function social() { return view('admin.pages.admin.configuracoes.social.index'); } public function analytics() { return view('admin.pages.admin.configuracoes.analytics.index'); } public function update($id, Factory $cache, Setting $setting) { $this->repository->findByName($setting); $cache->forget('settings'); return redirect('admin'); } } 

My SettingRepository:

 class SettingRepository { private $model; public function __construct(Setting $model) { $this->model = $model; } public function findByName($name){ return $this->model->where('name', $name)->update(); } } 

My blank form:

 {!! Form::model(config('settings'), ['class' => 's-form', 'route' => ['setting.update']]) !!} {{ method_field('PUT') }} <div class="s-form-item text"> <div class="item-title required">TΓ­tulo do artigo</div> {!! Form::text('title', null, ['placeholder' => 'Nome do site']) !!} @if($errors->has('title')) <div class="item-desc">{{ $errors->first('title') }}</div> @endif </div> <div class="s-form-item s-btn-group s-btns-right"> <a href="{{ url('admin') }}" class="s-btn cancel">Voltar</a> <input class="s-btn" type="submit" value="Atualizar"> </div> {!! Form::close() !!} 

But everything does not work. How to update values ​​in a table?

+7
php laravel
source share
3 answers

See improved answer in Update 2

I would add for this special service provider. It will read all your settings stored in the database and add them to the Laravels configuration. Thus, for parameters, there is only one database query, and you can access the configuration in all controllers and views as follows:

 config('settings.facebook'); 

Step 1. Create a service provider.

You can create a service provider using the wizard:

php artisan make:provider SettingsServiceProvider

This will create the app/Providers/SettingsServiceProvider.php file.

Step 2. Add this to the download method of the just created provider:

 /** * Bootstrap the application services. * * @return void */ public function boot() { // Laravel >= 5.2, use 'lists' instead of 'pluck' for Laravel <= 5.1 config()->set('settings', \App\Setting::pluck('value', 'name')->all()); } 

From the Laravel docs:

[Download method] is called after registration of all other service providers, which means that you have access to all other services that have been registered by the infrastructure.

http://laravel.com/docs/5.1/providers#the-boot-method

Step 3. Register the provider in your application.

Add this line to the providers array in config/app.php :

 App\Providers\SettingsServiceProvider::class, 

What is it. Happy coding!

Update: I want to add that the boot method supports dependency injection. Therefore, instead of hard coding \App\Setting you can add a repository / interface bound to the repository, which is great for testing.

Update 2: As indicated by Jeemusu in his comment , the application will query the database for each request. To prevent this, you can cache the settings. There are basically two ways you can do this.

  • Cache the data every time the administrator updates the settings.

  • Just remember the settings in the cache for some time and clear the cache every time the administrator updates the settings.

To make it more fault tolerant, I would use the second option. Caches may be deleted unintentionally. The first option will not work with new installations unless the administrator has set the settings or reinstalled after a server failure.

For the second option, change the method of loading Service providers:

 /** * Bootstrap the application services. * * @param \Illuminate\Contracts\Cache\Factory $cache * @param \App\Setting $settings * * @return void */ public function boot(Factory $cache, Setting $settings) { $settings = $cache->remember('settings', 60, function() use ($settings) { // Laravel >= 5.2, use 'lists' instead of 'pluck' for Laravel <= 5.1 return $settings->pluck('value', 'name')->all(); }); config()->set('settings', $settings); } 

Now you only need to make a cache to forget the settings key after the administrator updates the settings:

 /** * Updates the settings. * * @param int $id * @param \Illuminate\Contracts\Cache\Factory $cache * * @return \Illuminate\Http\RedirectResponse */ public function update($id, Factory $cache) { // ... // When the settings have been updated, clear the cache for the key 'settings': $cache->forget('settings'); // Eg, redirect back to the settings index page with a success flash message return redirect()->route('admin.settings.index') ->with('updated', true); } 
+16
source share

To avoid querying the database for each query, you must save the settings in the configuration file each time they are changed by the administrator / user.

  // Grab settings from database as a list $settings = \App\Setting::lists('value', 'name')->all(); // Generate and save config file $filePath = config_path() . '/settings.php'; $content = '<?php return ' . var_export($settings, true) . ';'; File::put($filePath, $content); 

The above will create a Laraval compatible configuration file that essentially just returns an array of key => values. The generated file will look something like this.

 <?php return array( name => 'value', name => 'value', ); 

Any php file in the /config directory will be automatically included by Laravel and the array variables available to your application through the config() helper:

 config('settings.variable_name'); 
+3
source share

You can store data in a database in the same way as usual in Laravel. \App\Setting::create() , \App\Setting::new() and other methods.

To use the values ​​in the blade, you can do {{\App\Setting::where('name','title')->pluck('value')}}

And you can also use for this area.

 class Setting extends Model { public function scopeFor($query, $settingName) { return $query->where('name', $settingName); } } 

then you can use \App\Setting::for('title')->pluck('value')

0
source share

All Articles