How to run an artisan command from a controller

Laravel: How to run an artisan command from a controller

Apart from within another command, I am not really sure I can think of a good reason to do this. But if you really want to call a Laravel command from a controller (or model, etc.) then you can use Artisan::call()

  1. Artisan::call('email:send', [
  2.         'user' => 1, '--queue' => 'default'
  3.     ]);

One interesting feature that I wasn't aware of until I just Googled this to get the right syntax is Artisan::queue(), which will process the command in the background (by your queue workers):

  1. Route::get('/foo', function () {
  2.     Artisan::queue('email:send', [
  3.         'user' => 1, '--queue' => 'default'
  4.     ]);
  5.  
  6.     //
  7. });

If you are calling a command from within another command you don't have to use the Artisan::call method - you can just do something like this:

  1. public function handle()
  2. {
  3.     $this->call('email:send', [
  4.         'user' => 1, '--queue' => 'default'
  5.     ]);
  6.  
  7.     //
  8. }

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to run an artisan command from a controller

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to add and remove items to an array in JS?

What does PEAR stand for?

How to sort an array in javascript?

How to add a name prefix to all routes in a group?

How to set environmental variables in your .htaccess file

How to set up an alias to map one directory to another destination

What is the spaceship operator (<=>) in PHP?

How to autoload helper files with composer?

What is camel case?

301 Redirect a single URL in .htaccess to a new location