Eloquent query in custom config file (/config&

2019-01-20 13:18发布

Trying to fire the following Eloquent query in a custom config file which is present in: /config directory in Laravel 5:

'array_name' =>(App\MyApp\Models\ModelName::lists('column_name', 'column_name')),

Getting the following error:

Fatal error: Call to a member function connection() on a non-object in /path/to/the/project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 3132

1条回答
Luminary・发光体
2楼-- · 2019-01-20 13:52

The config files that depend on database must be loaded lazily. Just put them inside a new config.lazy folder next to config folder and add the following method inside your app/Providers/COnfigServiceProvider.php

public function boot()
{
    $envConfigPath = config_path() . '/../config.lazy';
    $config = app('config');
    foreach (\Symfony\Component\Finder\Finder::create()->files()->name('*.php')->in($envConfigPath) as $file)
    {
        $key_name = basename($file->getRealPath(), '.php');
        $old_values = $config->get($key_name) ?: [];
        $new_values = require $file->getRealPath();
        $config->set($key_name, array_replace_recursive($old_values, $new_values));
    }
}
查看更多
登录 后发表回答