Search code examples
phplaravellaravel-5eloquentlaravel-5.3

User Object returns empty when trying to set class properties in constructor


public $tracksSystemDir;
public $contentSystemDir;


public function __construct(array $attributes = [])
{
    parent::__construct($attributes);

    // setup system directory paths
    $this->tracksSystemDir = public_path() . '/users/' . $this->reference . '/tracks/';
    $this->contentSystemDir = public_path() . '/users/' . $this->reference . '/content/';
}

when i try to user $this->tracksSystemDir it returns empty, in fact User object returns empty

User {#420 ▼
  #guarded: array:1 [▶]
  #dates: array:1 [▶]
  #hidden: array:2 [▶]
  +tracksSystemDir: "/home/vagrant/Code/9mmradio/public/storage/users//tracks/"
  +contentSystemDir: "/home/vagrant/Code/9mmradio/public/storage/users//content/"
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: []
  #original: []
  #relations: []
  #visible: []
  #appends: []
  #fillable: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  +exists: false
  +wasRecentlyCreated: false
  #forceDeleting: false
 }

This is returned user object when i dump the variable. i have googled about this and i found nothing and i went through the documentation couple of time and found nothing regarding too. So any help with this one is greatly appreciated :)


Solution

  • If you just want to add two properties to your user model, you can use Accessors as below:

    public function getTracksSystemDirAttribute()
    {
        return public_path() . '/users/' . $this->reference . '/tracks/';
    }
    

    then you can use it by saying:

    $user = User::find(1);
    $user->tracks_system_dir;
    

    And the same can be done for any other property.

    Note that the you should follow the naming as in the example. More on that in laravel documentation : Accessors