#mysql cannot find from .env using command while setup

3 messages · Page 1 of 1 (latest)

stone prairie
#

I am trying to create .sh file to easily configure my laravel app, I create a command to do most of the work, but when I select mysql database and update .env file, I always got sqlite error, below are my code and error:

public function handle()
{
    // ...
    $this->setupMySql();
    $this->runMigrationsWithSeeder();
}

private function setupMySql()
{
    $this->updateEnv('DB_CONNECTION', 'mysql');

    $host = text(
        label: 'What is the host of your database?',
        placeholder: '127.0.0.1',
        default: '127.0.0.1',
        required: true
    );

    $this->updateEnv('DB_HOST', $host);
    // ...
}

private function updateEnv($key, $value)
{
    $path = base_path('.env');

    if (File::exists($path)) {
        file_put_contents($path, preg_replace(
            "/^{$key}=.*/m",
            "{$key}={$value}",
            file_get_contents($path)
        ));
    }
}

private function runMigrationsWithSeeder()
{
    $this->call('migrate', [
        '--force' => true,
        '--seed' => true,
    ]);
}

Error: Database file at path [/project/database/database.sqlite] does not exist. Ensure this is an absolute path to the database. (Connection: sqlite, SQL: select exists (select 1 from sqlite_master where name = 'migrations' and type = 'table') as "exists")

The error come on first attempt, if I run again my .sh file, mysql load correct and it's working fine. so what should I miss here

amber nacelle
#

You talk about a .sh file, while not sharing it, you're only sharing an Artisan command?

When Laravel boots it evaluates the env file, then it wouldn't after that. It doesn't read the value from that file every time for example a DB name is read from the config, that would be incredibly inefficient.

stone prairie
#

My .sh file has simple command:

#!/bin/bash

# Ensure script is run from the project root
if [ ! -f "composer.json" ]; then
    echo "Please run this script from the project root directory."
    exit 1
fi

# Run composer install
echo "Installing Composer dependencies..."
composer install

# Run the installation command
php artisan install:project

I also has this reload env fn, but it looks like it's doesn't do the trick

private function reloadEnvironment()
{
    app()->bootstrapWith([
        \Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables::class,
    ]);
}