Search code examples
phplaravellaravel-4

Laravel 4.2, Artisan::call() ignoring --env option


I'm building an application that needs to create a new database, perform migrations and seed db data via a web page.

I'm trying to achieve this with the following code in Laravel 4.2. Note, this is within a controller I've setup.

Artisan::call("migrate", array(
    "--env" => "production"
));

No matter what environment I pass with the "--env" option, the environment that the migration is run on is the current environment that the site is currently running on. Ie. If I'm running on my local environment, and I run the above, it will execute the migration on the local environment which isn't what I'm looking to do.

If I run the equivalent command php artisan --env=production migrate from the command line, I get the results I'm looking to achieve. For the time being, I'm getting past this via passthru() but I'd like to take advantage of this Artisan facade if I can.

Does anyone know what's going on with this?


Solution

  • This isn't a pleasant way to do it, but it works.

    Assuming your Artisan environment is based on $_SERVER['HTTP_HOST'] and you know the HTTP_HOST that will load your environment then you can set it manually before calling start.php

    I used this to define the Artisan environment based on the base_url I was using in a Behat profile. That way I could configure fixture my database before running tests.

    /**
     * @BeforeSuite
     */
    public static function runFixtures(SuiteEvent $suiteEvent) {
    
        // Get the environment domain
        $parameters = $suiteEvent->getContextParameters();
        $baseUrl = $parameters['base_url'];
        $urlParts = parse_url($baseUrl);
        $_SERVER['HTTP_HOST'] = $urlParts['host'];
    
        // Now call start.php
        require_once 'bootstrap/start.php';
    
        // Call Artisan
        $stream = fopen('php://output', 'w');
        Artisan::call(
            'migrate:refresh',
            [
                '--seed' => true,
            ],
            new StreamOutput($stream)
        );
    }