Laravel 5 : Creating Console Commands

Anytime something causes me a great deal of time to figure out, I usually decide it’s worth posting. In this case it’s console commands in Laravel 5. Laravel 5 has just been released with some great improvements. Somewhat confusing is the usage of commands. Commands now appear to be some kind of event driven delegates. It is all well documented but not so well documented is wat happened to console commands, something we still need for our cronjobs and serious development work like running imports.

Here’s how to walk the walk in Laravel 5:
Generate the command
Console commands are now created with the following Artisan command :

In this case ‘GetMeABeerCommand’ is the class name of my command. You replace this with your own class name unless you need a beer too. The generated command will now be available in your App/Console/Commands folder.

Provide a console name and description
Now open this class and fill out a name for your command and a description :

The name your filled out will be the name you use to run the command from the console. Use alphanumeric characters, no spaces or funny stuff (I haven’t experimented with what characters are allowed but just stick to simple). This can be what ever you choose, but it’s logical to have it reflect what the command class does. So having a console command class ‘GetMeASodaCommand’ with a $name ‘command:get-beer’ doesn’t make much sense.

Register the console command
As with Laravel 4 you still have to register the command with a ServiceProvider. Laravel 5 installs with an AppServiceProvider (/App/Providers/) which you can use for this occassion, or you can create your own service provider. Just don’t forget to add it to the list/array of service providers in app.php if you decide to create your own.

You register the console command in the boot-method:

The ‘ABCD’ namespace here is my namespace I made up. In Laravel 5 you set your namespace with the Artisan command as you might now. The AppServiceProvider is generated at install and will already have the proper namespace. The only thing you have to to is add the lines in the boot-method. Notice how ‘get-beer’ is the name I provided above in the console command class.

Run the command

Go to your console (root of the website) and type :

You will now see a list of available options, your command will be listed under ‘commands’. You can run the command like this:

your-command-name in this case is the name you provided in the $name property of your console command class. In my case that’s ‘get-beer’. So I would run :

That’s all! I’m getting a beer. Happy coding!