How to make a Trait in Laravel

To create a trait by command I do it like this:

  php artisan make:command TraitMakeCommand

then you have this command in app/Console/Commands

it will create this commands extending from Command, but you have to change it to GeneratorCommand that is the one used to create Classes, so instead:

  use Illuminate\Console\Command;
  class TraitMakeCommand extends Command{

you should have this:

  use Illuminate\Console\GeneratorCommand;
  class TraitMakeCommand extends GeneratorCommand{

then, delete __construct() and handle() methods cause you are not gonna need them.

You need to create a file in app/Console/Commands/stubs called traits.stub which is going to be the base for your trait:

  <?php

  namespace TraitNamespace;

  trait {{class}}
  {
   // 
  }

and the code should be like this:

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

/**
 * 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';
}

After all this, you can create a trait with this command:

php artisan make:trait nameOfTheTrait

Well, laravel follows PSR-4 so you should place your traits in:

app/Traits

You then need to make sure you namespace your trait with that path, so place:

namespace App\Traits;

At the top of your trait

Then make sure when you save the file, the file name matches the trait name. So, if your trait is called FormatDates you need to save the file as FormatDates.php

Then 'use' it in your User model by adding:

use App\Traits\FormatDates;

at the top of your model, but below your namespace

and then add:

use FormatDates;

just inside the class, so for your User model, assuming you are using the laravel default, you would get:

use App\Traits\FormatDates;

class User extends Authenticatable
{
    use Notifiable, FormatDates;

...
}

And remember to dump the autoloader:

composer dump-autoload


Using this package you can create create Repository, Repository with Interface, Service, Trait form command line using php artisan command.

composer require theanik/laravel-more-command --dev

For create trait

php artisan make:trait {Trait Name}

Git repo : https://github.com/theanik/laravel-more-command

Tags:

Laravel 5.3