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.

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.

Thanks for taking the time to read this post! If you found this article useful and want to help support more work like this, please consider sponsoring my work on GitHub, or by checking out some merch.

 Sponsor on GitHub  Shop Merch