I am struggling to figure out how I can make a database query inside of a Laravel config file.
I currently use:
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.
You have a raw SQL query, and you are inside the config file. The config file has to be parsed before Laravel connects to the database.
You can simply connect to the database in pure php and do the query.
Connecting and querying a database in pure php is explained here: https://www.w3schools.com/php/php_mysql_connect.asp
$conn = mysqli_connect($servername, $username, $password);
$result = $conn->query('select version() as version');
$row = $result->fetch_assoc();
echo $row["version"];
$conn->close();
This should do it.
I tried out @jfadich's answer and found it wasn't quite solving the issue for me (laravel 5.4). I guess this is probably due to a different laravel version, but modifying his instructions I was able to get something working. By all means if I'm a bit wide of the mark in my approach please let me know, and I'll amend my answer.
So, I worked in the AppServiceProvicer itself, but you could also create a new one as previously suggested.
The line $this->app['config']->put('database.connections.mysql.version', $result->version);
was giving me an error (Call to undefined method Illuminate\Config\Repository::put())
I had a rummage in the Illuminate\Config\Repository file to see what methods it had defined and found a set()
method instead, which seems to work. I set my file up as so:
//in AppServiceProvider.php
use Illuminate\Contracts\Config\Repository; //allow setting of app config values
public function boot(Repository $appConfig)
{
$config = CustomConfig::first(); //get the values you want to use
$appConfig->set('configfile.username', $config->demo_username);
$appConfig->set('configfile.account', $config->demo_account);
}
I also came across the useful method all()
- a dd of $appConfig->all()
gave an easy way to check that the values had been set as intended.
Many thanks to @jfadich for putting me on the right path :)