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 return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to change the order that migrations happen?

How to set the timezone to UTC in .htaccess

How to get a route to directly show a view?

How to return JSON data to the user in Laravel?

How to get table column names from a database table in Eloquent?

What are PHP's PSRs?

How to make Apache force download of files (in .htaccess)

How to fix the MySQL related "Specified key was too long error" error in Laravel

How to force non www in htaccess