Reputation: 6593
I have a model, which inherits from the Toddish\Verify Laravel package (https://github.com/Toddish/Verify-L4/blob/master/src/Toddish/Verify/Models/User.php)
All I want to do is add some attributes:
use Toddish\Verify\Models\User as VerifyUser;
class User extends VerifyUser
{
public function __construct (array $attributes = array()) {
parent::__construct($attributes);
$this->fillable = array_merge ($this->fillable, array(
'salutation', 'title', 'firstname', 'lastname', 'phonenumber', 'mobilenumber'
));
}
}
When I run a test:
class UserTest extends TestCase {
public function testUserCreation () {
$user = User::create(
[
'username' => 'testusername',
'email' => '[email protected]',
'password' => 'testpassword',
'salutation' => 'MrTest',
'title' => 'MScTest',
'firstname' => 'Testfirstname',
'lastname' => 'Testlastname',
'phonenumber' => 'testPhoneNumber',
'mobilenumber' => 'testMobileNumber',
]
);
$this->assertEquals($user->salutation, 'MrTest');
$this->assertEquals($user->title, 'MScTest');
$this->assertEquals($user->firstname, 'Testfirstname');
$this->assertEquals($user->lastname, 'Testlastname');
$this->assertEquals($user->phonenumber, 'testPhoneNumber');
$this->assertEquals($user->mobilenumber, 'testMobileNumber');
}
}
I get the following:
1) UserTest::testUserCreation
Failed asserting that 'MrTest' matches expected null.
All of the asserts return null. But I checked and the database columns exist. So why is that attribute null?
EDIT:
If I swap the assert parameters:
$this->assertEquals('MrTest', $this->salutation);
I get this:
ErrorException: Undefined property: UserTest::$salutation
Upvotes: 2
Views: 386
Reputation: 8577
You will need to move the fillable override to be above the call to parent::__construct($attributes);
Making it:
public function __construct (array $attributes = array()) {
$this->fillable = array_merge ($this->fillable, array(
'salutation', 'title', 'firstname', 'lastname', 'phonenumber', 'mobilenumber'
));
parent::__construct($attributes);
}
This is because the main Model
classes constructor uses the fillable
array, so it needs to be set before the constructor is called.
[EDIT] Updated answer to include only the section that is required, and added some explanation of why it is the case
Upvotes: 3