// Хранение глобальных настроек сайта на laravel в БД
// 1. миграция
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSettingsTable extends Migration
{
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('value');
$table->string('default');
$table->enum('type', ['integer', 'money', 'string']);
$table->string('description');
});
}
public function down()
{
Schema::dropIfExists('settings');
}
}
//------------------------
// 2. Модель
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* App\Setting
*
* @method static \Illuminate\Database\Eloquent\Builder|\App\Setting newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Setting newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Setting query()
* @mixin \Eloquent
*/
class Setting extends Model
{
protected $primaryKey = 'key';
public $incrementing = false;
public $timestamps = false;
protected $keyType = 'string';
protected $fillable = ['key', 'value'];
}
//-----------------------------
// 3. Сервис-провайдер
<?php
namespace App\Providers;
use App\Setting;
use Illuminate\Support\ServiceProvider;
class SettingsServiceProvider extends ServiceProvider
{
public function boot()
{
//
}
public function register()
{
$this->app->singleton('settings', function ($app) {
$settings = [];
foreach (Setting::all() as $setting) {
switch ($setting->type) {
case 'integer':
$settings[$setting->key] = (integer)$setting->value ? (integer)$setting->value : (integer)$setting->default;
break;
case 'money':
$settings[$setting->key] = (float)round($setting->value, 2) ? (float)round($setting->value, 2) : (float)round($setting->default, 2);
break;
default:
$settings[$setting->key] = (string)$setting->value ? (string)$setting->value : (string)$setting->default;
}
}
return $settings;
});
}
}
//-------------------------
// 4. зарегистрировать SettingsServiceProvider провайдер
config/app.php
//--------------------------
// 5. в composer.json
"autoload": {
"files": [
"app/Helpers/helpers.php"
],
// 6. создаем свой хелпер ----------------
// файл /app/Helpers/helpers.php
<?php
use Illuminate\Support\Arr;
function setting($key)
{
return Arr::get(app('settings'), $key);
}
// 7. после создания файла выполнить composer dump-autoload
// 8. получить значение:
// где угодно вызываешь
setting('some_key')