Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

php - How to make database query inside a config file?

I am struggling to figure out how I can make a database query inside of a Laravel config file.

I currently use:

<?php
// config/database.php

$results = IlluminateSupportFacadesDB::select( IlluminateSupportFacadesDB::raw("select version()") );
$mysql_version =  $results[0]->{'version()'};
dd($mysql_version);

return [

...

But the error that I receive is that:

RuntimeException in Facade.php line 218:
A facade root has not been set.
in Facade.php line 218
at Facade::__callStatic('raw', array('select version()')) in database.php line 2
at require('/Users/test/code/clooud/config/database.php') in LoadConfiguration.php line 70
at LoadConfiguration->loadConfigurationFiles(object(Application), object(Repository)) in LoadConfiguration.php line 39
at LoadConfiguration->bootstrap(object(Application)) in Application.php line 208
at Application->bootstrapWith(array('Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables', 'Illuminate\Foundation\Bootstrap\LoadConfiguration', 'Illuminate\Foundation\Bootstrap\HandleExceptions', 'Illuminate\Foundation\Bootstrap\RegisterFacades', 'Illuminate\Foundation\Bootstrap\RegisterProviders', 'Illuminate\Foundation\Bootstrap\BootProviders')) in Kernel.php line 160
at Kernel->bootstrap() in Kernel.php line 144
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 116
at Kernel->handle(object(Request)) in index.php line 57
at require('/Users/test/code/clooud/public/index.php') in server.php line 128

How can I make sure that this query results in an output and resolve this error?

Thanks for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Leave a default or null value in your config/database.php file. Create a new service provider (either with the artisan command or manually)

php artisan make:provider DatabaseConfigProvider

Then add the new provider to the $providers array in your config/app.php file.

Finally add the following code to the boot() method.

public function boot()
{
    $result= DB::select('select version() as version')[0];
    $this->app['config']->put('database.connections.mysql.version', $result->version);
}

The key in the put() argument can be whatever you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...