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 select what columns to return when calling ::all()

An overview of every main PHP array function

How to Extract Query String (from a URL) Into an Associative Array in PHP

What are the predefined variables in PHP?

What is camel case?

How to check if a string contains a certain substring?

How to have a whitelist of IP addresses that can access files in .htaccess

How to set infinite execution time in a PHP script

How to replace whitespace with a single space

What kind of database field type should you (normally) use for foreign keys?