octal's avatar
Level 1

Execute Artisan command from code

Hello, I'm writing some maintenance functions for my website and I would like to know if there is a way to execute commands like

php artisan migrate:fresh

from a php script.

0 likes
5 replies
tykus's avatar

Here's how you would programmatically, just be careful what you are running:

Artisan::call('migrate:fresh')
1 like
octal's avatar
Level 1

@TYKUS - Thank you. I know, the script running this command will not run on server (will never be deployed) and on dev environment it requires special privileges to be run, so it's safe.

I used the Artisan::call('migrate:fresh') command and I'm having a new problem, in tinker environment I have this error:

Symfony/Component/Console/Exception/NamespaceNotFoundException with message 'There are no commands defined in the "migrate" namespace.'

From command line, the migrate:fresh comman run without any problem.

Is there a config file or location to update/register migrate:fresh commands ????

tykus's avatar

Where are you running this command?

octal's avatar
Level 1

From a static method in a controller. In fact the controller do a lot of maintenance work, and I added a static method to it in order to be able to instanciate it from Tinker envirnonment and refresh all my databse from scratch in order to automate unit-tests.

something like:

class MaintenanceController extends Controller
static public function initDB()
    {
        Artisan::call('migrate:fresh');
        App\Http\Controllers\MaintenanceController::setupDatabaseFromJSONFile('public/database/datasamples/samples.json');
    }
}

and from tinker environment I execute directly this method:

$ php artisan tinker
Psy Shell v0.9.9 (PHP 7.2.14 — cli) by Justin Hileman
>>> \App\Http\Controllers\MaintenanceController::initDB();
Symfony/Component/Console/Exception/NamespaceNotFoundException with message 'There are no commands defined in the "migrate" namespace.'
>>>
octal's avatar
Level 1

seems to me my controller method is not seeing any environment variable (the services are not registered nor loaded)

Please or to participate in this conversation.