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

Is multiple inheritance supported in PHP?

How to hide certain file types from directory listings

How to output (echo/print) content in PHP

How to select what columns to return when calling ::all()

How to convert between types in JS?

How to find out what version of Laravel you are using?

How could you include a custom function for every single time PHP runs?

How to enable the rewrite engine in .htaccess?

What are some ways you can log debug messages and data in JS?

How to review blog posts (written by other users) before they get published on your WordPress blog?