|

How to Create Laravel Artisan Console Commands

How to Create Laravel Artisan Console Commands

Part of working with Laravel is not only creating the web based, or HTTP focused functionality, but also leveraging Artisan. Artisan is the part of your application that operates from the command line. If you’re used to strictly graphical user interface based applications, Artisan will be a bit to understand at first. With time however, you’ll begin to appreciate just how much you can accomplish via very simple commands you type in at the console. You may already be familiar with doing things like creating migrations, clearing the cache, generating boilerplate code for controllers, events, jobs, middleware, tests, and more. All of this is accomplished through Artisan. Now comes the fun part, you can create your own custom commands as well which will be added to the list of Artisan commands on your application. Let’s see how.


php artisan inspire

First, we’ll take a look at the inspiring quote generator that ships with Laravel. In order to test it out, we had to uncomment a line in the protected $commands property of the Kernel class. If you want to follow along, find your Kernel.php in app/Console and it should look like this.

With this, we have turned on the ability to use this command. In other words, it is now registered. Let’s go ahead and take it for a test run.

vagrant@homestead:~/Code/lpg$ php artisan inspire
Very little is needed to make a happy life. – Marcus Antoninus

vagrant@homestead:~/Code/lpg$ php artisan inspire
Simplicity is the essence of happiness. – Cedric Bledsoe

vagrant@homestead:~/Code/lpg$ php artisan inspire
He who is contented is rich. – Laozi

So this is pretty neat. We turned on the ability to use this command, and took it for a test run. We can see from the above output that we got some inspiring quotes. As a simple exercise, let’s say you wanted to create your own quote generator and run it from the command line. How would you do that? Well, it turns out it’s pretty easy – let’s give it a shot.


php artisan make:console

The first thing you will do is to use the command php artisan make:console from the root directory of your Laravel project. This is typically the name of your project. In our case all of our Laravel files are contained in the lpg directory, so you can see we ran artisan from this location in the examples above. This is where your actual artisan.php file lives, and this is the file you are actually executing when you run php artisan. Yes this is second nature to the more experienced developers, but for newcomers to the command line and/or Laravel, this information will help you. Anyhow, when running php artisan make:console it is going to expect the name parameter. If you try to run the command without it, you will get an error such as “[Symfony\Component\Console\Exception\RuntimeException] Not enough arguments (missing: “name”).” Here is our stab at creating a new console command class.

vagrant@homestead:~/Code/lpg$ php artisan make:console QuoteGenerator
Console command created successfully.

It appears this worked. If we now check in app/Console/Commands we will find a new class file of QuoteGenerator.php and it contains this boilerplate for us.

You might be thinking, ok great – so what do I do with this? We’re going to start super simple. The first thing you will do is to modify the signature property. This is what determines what you see as the command when you run php artisan. Change that signature to the following.

Great! Now, let’s register, or turn on, this command. To do this, navigate to app/Console/Kernel.php and add the entry for this newly generated class to the $commands array like so.

Our command is now registered and available to use. To see it in the menu, just run php artisan list quote.

vagrant@homestead:~/Code/lpg$ php artisan list quote
Laravel Framework version 5.2.20

Usage:
command [options] [arguments]

Options:
-h, –help Display this help message
-q, –quiet Do not output any message
-V, –version Display this application version
–ansi Force ANSI output
–no-ansi Disable ANSI output
-n, –no-interaction Do not ask any interactive question
–env[=ENV] The environment the command should run under.
-v|vv|vvv, –verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose
output and 3 for debug

Available commands for the “quote” namespace:
quote:generate Command description

Note: We can see from the output above that Laravel is indeed now aware of a quote:generate command. Our command still has a generic description. Let’s change that by giving a custom description to what our command will do. All we have to do is update the $description property in our QuoteGenerator class to something like so.

With this update, we can check it out on the console one more time.

vagrant@homestead:~/Code/lpg$ php artisan list quote

Available commands for the “quote” namespace:
quote:generate Generate a random quote.

Notice our new command description is now active.


Add logic to handle()

Right now, our newly created command does a whole lot of nothing. Let’s test it.

vagrant@homestead:~/Code/lpg$ php artisan quote:generate
vagrant@homestead:~/Code/lpg$

Nothing happened. We’re right back at the command line with no effect. The place to add logic to your command is in the handle() method of your newly created class. If we navigate to our app/Console/Commands/QuoteGenerator.php class, we find that it has a public function named handle(). This is where the action happens. When your command runs, any logic contained in this function will be processed. We wanted to create some quotes, and randomly display them to the console. Let’s add some logic to do this. We will take inspiration from iamdeveloper to power our quotes.

Check it out!
vagrant@homestead:~/Code/lpg$ php artisan quote:generate
The software development process i can’t fix this *crisis of confidence* *questions career* *questions life* oh it was a typo, cool

vagrant@homestead:~/Code/lpg$ php artisan quote:generate
Never trust a developer wearing a suit.

vagrant@homestead:~/Code/lpg$ php artisan quote:generate
Give a man a fish and you feed him for a day, Teach a man to fish and you feed him for a lifetime, Give a startup $$ and they’ll waste it.

vagrant@homestead:~/Code/lpg$ php artisan quote:generate
“The Top 100 JavaScript Frameworks of 2015″ ಠ_ಠ this is an issue.

vagrant@homestead:~/Code/lpg$ php artisan quote:generate
waiter, waiter lemme guess, there’s a fly in your soup? no i just wanted to say I use Vim


Customizing the command signature with arguments and options

So we have successfully created our very own artisan command. One thing we left out, at least so far, is the concept of arguments and options in the command signature. With our current quote generator, we simply run the command and it outputs a quote. Let’s customize the command so that it will address the user who is running the command. This is a really slick feature as all you need to do is update the string contained within the $signature property of your command class. The following example allows you to specify a name argument, or if not, set the default to “friend”.

We make use of this argument in our handle() method like so.

Testing it out, we can see this work.
vagrant@homestead:~/Code/lpg$ php artisan quote:generate Leo
Hey Leo, check this out: “The Top 100 JavaScript Frameworks of 2015″ ಠ_ಠ this is an issue.

vagrant@homestead:~/Code/lpg$ php artisan quote:generate Katie
Hey Katie, check this out: project manager: i know enough coding to be dangerous *winks* literally ruins entire codebase

vagrant@homestead:~/Code/lpg$ php artisan quote:generate Jim
Hey Jim, check this out: Never trust a developer wearing a suit.

If we omit the name argument, it still works.
vagrant@homestead:~/Code/lpg$ php artisan quote:generate
Hey friend, check this out: The software development process i can’t fix this *crisis of confidence* *questions career* *questions life* oh it was a typo, cool


Integration Options

We can also make use of options in the artisan command. Let’s add an option to customize the greeting to the person running the command.

We can now integrate this into our handle() method like so.

Giving it a quick test run, we can see it works well.
vagrant@homestead:~/Code/lpg$ php artisan quote:generate --greeting="YOU GOTTA SEE THIS"
Hey friend, YOU GOTTA SEE THIS: “Made with love” I call BS.


How to Create Laravel Artisan Console Commands Summary

In this tutorial, we saw how to create our very own artisan console commands with the Laravel framework. We saw that we can easily bootstrap the boilerplate for this with the command php artisan make:console name. Once we create the class, we need to fill out it’s $signature and $description properties like we covered. By adding logic to the handle() method, we can determine what the command actually does for us. Once all of this is in place, we can’t forget to turn on, or register the command within the Kernel.php file of Console. In addition to these basic tasks, we took a look at the great ability to define arguments and options in a very simple way right in the $signature property.