简体   繁体   English

config \\ app.php从数据库获取值

[英]config\app.php getting values from database

I'm saving laravel app settings in database, but i can't use this trick in config\\app.php . 我正在将laravel应用程序设置保存在数据库中,但无法在config\\app.php使用此技巧。 When i use in models or controllers with setting('app.name') or \\setting('app.url') working. 当我在具有setting('app.name')\\setting('app.url')工作的模型或控制器中使用时。 But when i use this in config\\app.php i'm getting this error; 但是当我在config\\app.php使用它时,我得到了这个错误。

Fatal error: Uncaught RuntimeException: A facade root has not been set. in /home/vagrant/SeraEnerji/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 234
( ! ) RuntimeException: A facade root has not been set. in /home/vagrant/SeraEnerji/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 234
Call Stack
#   Time    Memory  Function    Location
1   0.0001  401512  {main}( )   .../index.php:0
2   0.0252  821816  App\Http\Kernel->handle( )  .../index.php:55
3   0.0459  1270304 App\Http\Kernel->renderException( ) .../Kernel.php:120
4   0.0459  1270304 App\Exceptions\Handler->render( )   .../Kernel.php:326
5   0.0459  1270304 App\Exceptions\Handler->render( )   .../Handler.php:49
6   0.0463  1272856 App\Exceptions\Handler->prepareResponse( )  .../Handler.php:190
7   0.0467  1279088 App\Exceptions\Handler->renderHttpException( )  .../Handler.php:293
8   0.0467  1279088 App\Exceptions\Handler->registerErrorViewPaths( )   .../Handler.php:378
9   0.0514  1359464 Illuminate\Support\Facades\Facade::replaceNamespace( )  .../Handler.php:401
10  0.0514  1359840 Illuminate\Support\Facades\Facade::__callStatic( )  .../Handler.php:401

How can i get values from database for config\\app.php ? 如何从config\\app.php数据库获取值? İnfo: I'm followed this guide, https://www.qcode.in/save-laravel-app-settings-in-database/ İnfo:我遵循了本指南, https ://www.qcode.in/save-laravel-app-settings-in-database/

My table: 我的桌子:

id  |  name                |    val  
----------------------------------------
1   | app_name             | Site Name
2   | app_description      | Site Description
3   | app_url              | example.com
app\utils\helpers.php

<?php
if (! function_exists('setting')) {
    function setting($key, $default = null)
    {
        if (is_null($key)) {
            return new \App\Models\Setting\Setting();
        }
        if (is_array($key)) {
            return \App\Models\Setting::set($key[0], $key[1]);
        }
        $value = \App\Models\Setting::get($key);
        return is_null($value) ? value($default) : $value;
    }
}
app\models\setting.php

<?php

namespace App\Models;

use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Setting extends Model
{
    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * Add a settings value
     *
     * @param $key
     * @param $val
     * @param string $type
     * @return bool
     */
    public static function add($key, $val, $type = 'string')
    {
        if ( self::has($key) ) {
            return self::set($key, $val, $type);
        }

        return self::create(['name' => $key, 'val' => $val, 'type' => $type]) ? $val : false;
    }

    /**
     * Get a settings value
     *
     * @param $key
     * @param null $default
     * @return bool|int|mixed
     */
    public static function get($key, $default = null)
    {
        if ( self::has($key) ) {
            $setting = self::getAllSettings()->where('name', $key)->first();
            return self::castValue($setting->val, $setting->type);
        }

        return self::getDefaultValue($key, $default);
    }

    /**
     * Set a value for setting
     *
     * @param $key
     * @param $val
     * @param string $type
     * @return bool
     */
    public static function set($key, $val, $type = 'string')
    {
        if ( $setting = self::getAllSettings()->where('name', $key)->first() ) {
            return $setting->update([
                'name' => $key,
                'val' => $val,
                'type' => $type]) ? $val : false;
        }

        return self::add($key, $val, $type);
    }

    /**
     * Remove a setting
     *
     * @param $key
     * @return bool
     */
    public static function remove($key)
    {
        if( self::has($key) ) {
            return self::whereName($key)->delete();
        }

        return false;
    }

    /**
     * Check if setting exists
     *
     * @param $key
     * @return bool
     */
    public static function has($key)
    {
        return (boolean) self::getAllSettings()->whereStrict('name', $key)->count();
    }

    /**
     * Get the validation rules for setting fields
     *
     * @return array
     */
    public static function getValidationRules()
    {
        return self::getDefinedSettingFields()->pluck('rules', 'name')
            ->reject(function ($val) {
                return is_null($val);
            })->toArray();
    }

    /**
     * Get the data type of a setting
     *
     * @param $field
     * @return mixed
     */
    public static function getDataType($field)
    {
        $type  = self::getDefinedSettingFields()
            ->pluck('data', 'name')
            ->get($field);

        return is_null($type) ? 'string' : $type;
    }

    /**
     * Get default value for a setting
     *
     * @param $field
     * @return mixed
     */
    public static function getDefaultValueForField($field)
    {
        return self::getDefinedSettingFields()
            ->pluck('value', 'name')
            ->get($field);
    }

    /**
     * Get default value from config if no value passed
     *
     * @param $key
     * @param $default
     * @return mixed
     */
    private static function getDefaultValue($key, $default)
    {
        return is_null($default) ? self::getDefaultValueForField($key) : $default;
    }

    /**
     * Get all the settings fields from config
     *
     * @return Collection
     */
    private static function getDefinedSettingFields()
    {
        return collect(config('setting_fields'))->pluck('inputs')->flatten(1);
    }

    /**
     * caste value into respective type
     *
     * @param $val
     * @param $castTo
     * @return bool|int
     */
    private static function castValue($val, $castTo)
    {
        switch ($castTo) {
            case 'int':
            case 'integer':
                return intval($val);
                break;

            case 'bool':
            case 'boolean':
                return boolval($val);
                break;

            default:
                return $val;
        }
    }

    /**
     * Get all the settings
     *
     * @return mixed
     */
    public static function getAllSettings()
    {
        return Cache::rememberForever('settings.all', function() {
            return self::all();
        });
    }

    /**
     * Flush the cache
     */
    public static function flushCache()
    {
        Cache::forget('settings.all');
    }

    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        static::updated(function () {
            self::flushCache();
        });

        static::created(function() {
            self::flushCache();
        });
    }
}

Okay i found to solution. 好吧,我找到了解决方案。 If there are people who have the same problem with me, the solution I found is as follows. 如果有人对我有相同的问题,我找到的解决方法如下。

App\Providers\AppServiceProvider.php

<?php

namespace App\Providers;

use App\Models\Setting;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $settings = Setting::all()->pluck('val', 'name');
        config()->set('settings', $settings);
        Config::set([
            'app.name' => \config('settings.app_name'),
            'app.url' => \config('settings.app_url'),
        ]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM