Laravel: Calling Artisan Commands From Your Application

March 27, 2014 —John Koster

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

1<?php
2 
3Route::get('example', function()
4{
5 // Call and Artisan command from within your application.
6 Artisan::call('db:seed');
7});

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:

1<?php
2 
3Route::get('example', function()
4{
5 // Call and Artisan command from within your application and
6 // pass an argument.
7 Artisan::call('db:seed', array('--class' => 'UserTableSeeder'));
8});

#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:

1<?php
2 
3Route::get('example', function()
4{
5 // Call and Artisan command from within your application and
6 // pass an argument.
7 Artisan::call('migrate', array('--path' => '../app/database/migrations'));
8});

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

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.