Dennis Smink

Laravel Trait Make Command

Jun 4, 2020 · 1 minute read

I personally love Traits, exporting functions/logic that can be used by multiple classes is so awesome and clean. You get more standardized and readable code by using Traits.

In this tutorial i’ll explain how to make an easy make:trait command so you can easily whip up traits.

First, start of by making the command:

php artisan make:command TraitMakeCommand

Now open up app/console/commands/TraitMakeCommand.php and make the contents as following:

<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

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

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

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Trait';

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return __DIR__ . '/stubs/trait.stub';
    }

    /**
     * Get the default namespace for the class.
     *
     * @param  string $rootNamespace
     *
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace . '\Traits';
    }
}

Next, register this command in your Kernel.php @ app/console/kernel.php

Lastly we need a stub so we know what the default contents are within the created trait.

Place this stub inside this path: app/console/commands/stubs/trait.stub:

<?php

namespace DummyNamespace;

trait DummyClass
{
    //
}

Thats it! You can now execute this command to create your trait:

php artisan make:trait MyTrait

If you have any questions, let me know!