Thursday, April 13, 2017

Laravel 5 Eloquent custom constructor not working

I'm trying to get a custom constructor to work with a model extending an Eloquent model in Laravel 5.4 I already make sure to call the parent constructor, but it seems that nothing that I do takes any effect at all after that.

Here is my __construct function:

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

    $this->users();
}

And here is the users() method:

public function users()
{
    $this->users = collect();

    foreach($this->employees as $employee) {
        $this->users = $this->users->push($employee->user);
    }

    $this->users = $this->users->unique();
}

In this example employee is a class that links a user to a store and also defines their jobs. However, it doesn't matter what I try to assign. I have also tried just assigning a garbage variable in the constructor with

$this->foo = 'bar';

or even trying to overwrite an attribute, such as

$this->name = 'foobar';

to no avail. I've also tried to simply switch the order of the code calling parent::__construct() before or after my code and nothing at all changes.

Any help would be greatly appreciated!



via aylnon

Advertisement