__ design on the bright Laravel model

I have a custom set that I run in the __construct method on my model.

This is the property I want to set.

  protected $directory; 

My constructor

  public function __construct() { $this->directory = $this->setDirectory(); } 

Installer:

  public function setDirectory() { if(!is_null($this->student_id)){ return $this->student_id; }else{ return 'applicant_' . $this->applicant_id; } } 

My problem is that inside my setter, $this->student_id (which is an attribute of the model retrieved from the database) returns null . When I dd($this) from inside my setter, I notice that my #attributes:[] is an empty array.
Thus, model attributes are not set until __construct() is run. How to set the $directory attribute in my build method?

+5
source share
1 answer

You need to change your constructor to:

 public function __construct(array $attributes = array()) { parent::__construct($attributes); $this->directory = $this->setDirectory(); } 

The first line ( parent::__construct() ) will run the Eloquent Model own constructor method before running your code, which will configure all the attributes for you. Also, a change in the signature of the constructor method should continue to support the use that Laravel expects: $model = new Post(['id' => 5, 'title' => 'My Post']);

The thumb rule really should always be remembered when extending a class to make sure that you do not override the existing method so that it no longer runs (this is especially important with the magic of __construct , __get , etc.). You can check the source of the source file to see if it includes this method.

+20
source

All Articles