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 namespace a Laravel route group?

What are the main error types in PHP

How to split a string into an array, in JS

How to find the average value of items in a Laravel Collection?

How to generate an array for a dropdown (with ['key' => 'value']) suitable for a dropdown, from a Laravel collection of Eloquent objects?

How to group a SQL statement in brackets/parenthesis

How to get the type of a variable in JS?

What are generators in PHP, and how do they compare to arrays?

How to change the order that migrations happen?

How to remove .php from the end of URLs with .htaccess