LARAVEL

How to create a custom Artisan Command in Laravel 5


Several artisan commands come shipped with Laravel 5.

Run php artisan list and you will get all the artisan commands that you can use.

Some of the most popular ones that are used on a daily basis are:

php artisan serve, php artisan down, php artisan up, php artisan make:migration.

Introduction

The more your application grows, the more functionalities it possesses, the more you want to automate several tasks.

Let’s learn how to create a custom artisan command to show funny faces in the console.

Let’s give fellow software developers and IT administrators the ability to be entertained when they are bored.

We will call the name of the command faces.

1. Open your terminal and run this command:

php artisan make:console Faces

This creates a file called Faces.php in the app/Console/Commands directory.

Open the file Faces.php

Faces.php 

Now, change the value of $signature  to:

and $description to:

2. Let’s create the logic for displaying random faces.

Create a function like so:

Look at the function carefully. We are using the Collection Facade and calling the random method it offers to help us return a random face.

One more thing, we need to require the Collection class at the top of the file like so:

To send output to the console, we can use line, info, comment, question and error methods from Laravel Command class.

3. Let’s register the command

Open app/Console/Kernel.php file and add the name of the class to the $commands array like so:

Now, go to the terminal and run php artisan list, you will see the name of your command listed:

The faces command is listed with the description. Awesome! :smile:

4. Run the command

Now, run php artisan faces in your terminal.

It shows a different face every time the command is been run in the terminal

Conclusion

Now, we know how to create custom Artisan commands in Laravel 5.

This is barely scratching the surface, there is a lot more you can do. You can programme it to receive input from the console.

You can also program it to receive results from an external service like an API.

You can program it to scan, make, list and delete directories.

It all solely depends on your idea.

NOTE: The link to the source code is here

Please, if you have any question or observations, let me know in the comments section. :smile:

PROSPER OTEMUYIWA

About PROSPER OTEMUYIWA

Food Ninja, Code Slinger, Technical Trainer, Accidental Writer, Open Source Advocate and Developer Evangelist.