62

Where to make the file if i want to use this trait on my Models

How should this file look like if i want to have this trait inside:

trait FormatDates
{
    protected $newDateFormat = 'd.m.Y H:i';


    // save the date in UTC format in DB table
    public function setCreatedAtAttribute($date){

        $this->attributes['created_at'] = Carbon::parse($date);

    }

    // convert the UTC format to my format
    public function getCreatedAtAttribute($date){

        return Carbon::parse($date)->format($this->newDateFormat);

    }

    // save the date in UTC format in DB table
    public function setUpdatedAtAttribute($date){

        $this->attributes['updated_at'] = Carbon::parse($date);

    }

    // convert the UTC format to my format
    public function getUpdatedAtAttribute($date){

        return Carbon::parse($date)->format($this->newDateFormat);

    }

    // save the date in UTC format in DB table
    public function setDeletedAtAttribute($date){

        $this->attributes['deleted_at'] = Carbon::parse($date);

    }

    // convert the UTC format to my format
    public function getDeletedAtAttribute($date){

        return Carbon::parse($date)->format($this->newDateFormat);

    }
}

And how to apply it for example on a User Model class...

lewis4u
  • 14,256
  • 18
  • 107
  • 148

3 Answers3

133

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

craig_h
  • 31,871
  • 6
  • 59
  • 68
  • I have created the file MyTraits.php and it's in the App\Traits folder and in my User Model Class i have namespace App\Traits; use App\Traits\FormatDates; use Notifiable, SoftDeletes, FormatDates; And it doesn't work...Trait cannot be found.....if you could help me please over TeamViewer??? – lewis4u Oct 27 '16 at 15:46
  • 1
    Make sure you save the file as `FormatDates.php` to match your class name. – craig_h Oct 27 '16 at 15:47
  • That fixed it....now i get another error Class '\App\User' not found..??? – lewis4u Oct 27 '16 at 15:49
  • 1
    It looks like you've added a namespace to your User model, the namespace for the User model should be `namespace App;`, so make sure you haven't included `namespace App\Traits` in your User model – craig_h Oct 27 '16 at 15:50
  • Do you have just 5 min please i have one more problem...i can't change the locale..it is changed in config/app.php but it doesn't apply – lewis4u Oct 27 '16 at 15:51
  • if we could chat somwhere to not to spam this question? Please – lewis4u Oct 27 '16 at 15:53
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/126844/discussion-between-lewis4u-and-craig-h). – lewis4u Oct 27 '16 at 15:54
  • @craig_h Great answer. Could you update the top to say you are saving the file with name FormatDates.php in folder app/Traits. I was a little confused till I saw your reply comments. Would make the answer more complete. +1 – BrinkDaDrink Jul 21 '17 at 23:07
  • @craig_h Why should I use App\Traits\FormatDates; outside the class and then use FormatDates; again inside it ?? – Rowayda Khayri Jul 12 '18 at 13:46
  • ^ that's how traits or any other class inside class are used. Otherwise you need to write the whole namespace of the trait/class you want to use and that can be very long and hard to read. – lewis4u Feb 08 '21 at 07:27
  • Where did you read that all traits should be in the `app/Traits` directory? – Lucas Silva Mar 01 '21 at 19:48
  • @LucasSilva I was probably just trying to keep things simple, but you can obviously put them wherever you want, just as long as your namespace matches the directory structure. – craig_h Mar 01 '21 at 20:12
  • When I read this after 4 years... I admire @craig_h for his patience :D (I was at 3450 points at that time) – lewis4u Jul 09 '21 at 12:49
29

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
Evan
  • 1,004
  • 11
  • 12
3

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

Anik Anwar
  • 625
  • 5
  • 11