Tag Archives: Command

Laravel 8: How to Use command to create custom files

1. First create a command file with the make: command command command

php artisan make:command ServicesCommand

2. A servicescommand file will be generated under app\console\commands

<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

// GeneratorCommand
class ServicesCommand extends GeneratorCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $name = 'make:service'; 

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new service';

    /**
     * The console command type.
     */
    protected $type = 'service'; 


    // The template that the generated file depends on can be set by yourself
    // I put the files here in the same level as the Stubs directory
    protected function getStub()
    {
        return __DIR__.'/Stubs/CreateService.stub';
    }

    // Namespaces to be used in the template
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Services';
    }
}

3. Create stubs\createservice Stub file

<?php

namespace {{ namespace }};

class {{ class }}
{
  // You can add the required code yourself      
}

4. Testing

// Check if the command
php artisan list

// Create Test
php artisan make:service TestService

5. Other

In the lower version, the class needs to be registered in the commands attribute of commands \ kernel.

protected $commands = [
  ServicesCommand::class,      
];