Skip to content

Instantly share code, notes, and snippets.

@anuzpandey
Created April 21, 2023 18:11
Show Gist options
  • Save anuzpandey/dd5de6e66829c4d467022e2d9f488509 to your computer and use it in GitHub Desktop.
Save anuzpandey/dd5de6e66829c4d467022e2d9f488509 to your computer and use it in GitHub Desktop.
Custom Command to create Traits with stubs

Stub File

// trait.stub
<?php

namespace App\Traits;

trait {{ traitName }} {

}

Command

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class ArtisanMakeTraitCommand extends Command
{
    protected $signature = 'make:trait {name}';

    protected $description = 'Create a new trait';

    public function handle(): void
    {
        $name = $this->argument('name');

        $name = Str::substr($name, -5) === 'Trait'
            ? $name
            : $name . 'Trait';

        $path = app_path('Traits/' . $name . '.php');
        if (File::exists($path)) {
            $this->error('Trait already exists!');

            return;
        }

        $stub = File::get(base_path('stubs/trait.stub'));
        $stub = Str::replace('{{ traitName }}', $name, $stub);

        File::put($path, $stub);

        $this->info('Trait created successfully.');
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment