Making a custom Artisan Command in Laravel 5.8

Introduction

Laravel is packaged with lots of commands to help developers speed up the development process. Some of them include .php artisan serve , php artisan:make modeletc.

In my Laravel projects, I use a structure that helps me separate different layers and logic from each other.
In the words of my technical director, “Your controller should do as little as possible

So in most of my projects, I create Services classes that handle all logic and the Repository classes that handle all form of connections to the database.
So in simple terms, the Controller calls the Service if there is a need for any logic while the services class calls the Repository if there is any need to connect to the database.

Anyways, in one of my recent projects, I decided to write a command that helps me generate my Services and Repository classes to speed up my work.

Building the Command

First, you must understand that Laravel uses .stub files as templates, and replaces the tokens inside the template to generate your custom class or file.

Now let's make a custom command

  1. Run php artisan make:command AddService
    This command will generate the AddService.php in the app\Console\Commands
AddService created with the artisan command in the Commands directory

2. Create a dummy stub file, named services.stub, in the directory app/Console/Commands/Stubs/service.stub

services stub created.

3. Add the following to the services.stub file

<?php

namespace DummyNamespace;


class DummyClass
{

}

4. Now Open the AddService.php in the commands directory and replace with the following

<?php

namespace
App\Console\Commands;


use Illuminate\Console\GeneratorCommand;
class AddServices extends GeneratorCommand
{
/**
* The console command name.
*
*
@var string
*/
protected $name = 'make:service';
/**
* The console command description.
*
*
@var string
*/
protected $description = 'Create a new service class';
/**
* The type of class being generated.
*
*
@var string
*/
protected $type = 'Services';
/**
* Get the stub file for the generator.
*
*
@return string
*/
protected function getStub()
{
return __DIR__.'/stubs/services.stub';
}
/**
* Get the default namespace for the class.
*
*
@param string $rootNamespace
*
@return string
*/

protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Services';
}
}

5. Now we can make a new service by using php artisan make:service TeachersService 
The command will create the TeacherService.php class inside my Services directory.

6. You can also run php artisan list and you will find that your command is also listed


Conclusion

Laravel is a great framework that has been making life easy for developers to build a great application.


Thanks for reading!