Laravel: Calling Artisan Commands From Your Application

2 min read

This little tip will show you how to run Artisan commands from within your applications code, if you need to.

<?php

Route::get('example', function()
{
    // Call and Artisan command from within your application.
    Artisan::call('db:seed');
});

If you need to specify command options, you can do this by passing an array as the second argument to the call method. The array should be constructed so that the keys are the name of the option, and the value is the value of the option. If we were to take the example from the Laravel docs where we pass in the UserTableSeeder as an option, we could do it like so:

<?php

Route::get('example', function()
{
    // Call and Artisan command from within your application and
    // pass an argument.
    Artisan::call('db:seed', array('--class' => 'UserTableSeeder'));
});

Paths Are Relative!

When calling Artisan commands from your application, such as running migrations (if you are building a web utility to run your migrations), the paths are relative to where the calling file is located. Usually Artisan commands are ran from the command line at root of your application.

As an example, running php artisan migrate --path=app/database/migrations on the command line would have to be ran like this from your application:

<?php

Route::get('example', function()
{
    // Call and Artisan command from within your application and
    // pass an argument.
    Artisan::call('migrate', array('--path' => '../app/database/migrations'));
});

You could even simplify this further by leveraging Laravel's >path helper functions.

Comments

There are no comments. Be the first to comment!

Up next