Search code examples
phplaraveloopcoding-styletraits

Traits inside Models


For example I have a model class. I want it to be Timestampable. It means a model must have created_at, updated_at fields and getters for them.

<?php

trait Timestampable {

    protected $created_at;
    protected $updated_at;

    public function getCreatedAt() {}
    public function getUpdatedAt() {}   

}

class User extends Model {

    use Timestampable;

    protected $id;
    protected $name;
}

Is it ok? Or I have to move timestampable fields in to the model?

Authenticatable Trait (Laravel)

In Laravel they don't place their fields in traits, but only some of them. Of course it works while these fields exist in class where our trait was used. But we lose some advantages in IDE autocompletion and make our code ambiguous.


Solution

  • By default all Model have already property created_at and updated_at because the Illuminate\Database\Eloquent\Model has already use the Illuminate\Database\Eloquent\Concerns\HasTimestamps which define the getCreatedAtColumn and getUpdatedAtColumn methods HasTimestamps method getCreatedAtColumn

    You don't have to define your own HasTimestamps it isn't important because all the implementation that provide that behavior already exist