Search code examples
phplaravel-4development-environmentdatabase-migration

Laravel not detecting environemnt correct


I'm new to Laravel and I'd like some help please.

First of all I tried to set up my 'development' environment according to the machine name, so I did this

die(gethostname()); // output the machine name, in my case is ΛΥΚΟΣ-PC
$env = $app->detectEnvironment(array(

    'local' => array('ΛΥΚΟΣ-PC'),

));

but didn't seem to work. So I followed the instructions on Environment Configuration and did the following

$env = $app->detectEnvironment(function(){

    switch ($_SERVER['HTTP_HOST']) {
        case 'localhost':
            return 'local';
        break;

        default:
            return 'production';
        break;
    }
});
die($env); // outputs 'local'

The problem is that when I tried to do some migrations, I typed in the command line:

$ php artisan migrate

in order to create the table, but I get this

*******************************
*  Application in Production! *
*******************************

Do you really want to run this command?

and if I proceed I get 'Access denied for user ''@'localhost' to database 'forge'.

Well, I guess this problem has to do with the environtment configuration. Any ideas how to fix it?


Solution

  • The reason why the $_SERVER['HTTP_HOST'] solution doesn't work with Artisan is that $_SERVER['HTTP_HOST'] variable is only available when launched through a web server.

    'local' => array('ΛΥΚΟΣ-PC') should work, might have something to do with the special characters.

    I set my environment based on the laravel path:

    $env = $app->detectEnvironment(array(
    
        'local' => strpos(getcwd(), '/local')>-1,
        'staging' => strpos(getcwd(), '/staging')>-1,
    
    ));
    

    So the environment is set to local if /local is part of the path. Note: You might have to replace / with \ on Windows.

    You can also specify the environment to Artisan:

    php artisan migrate --env=local
    

    But I would recommend you have your environments in order, makes everything easier. And less chance of messing up your production.