문제

I am using the Toddish/Verify library for Laravel as it includes 99% of what I need for my project. All I need is to add some fields.

I have added them in a migration, and I want to add them also to mass creation:

use Toddish\Verify\Models\User as VerifyUser;

class User extends VerifyUser
{
    public function __construct () {
        array_merge ($this->fillable, array(
            'salutation', 'title', 'firstname', 'lastname', 'phonenumber', 'mobilenumber'
        ));
    }
}

However, when I run my creation test:

public function testUserCreation () {
    $user = User::create(
        [
            'username' => 'testusername',
            'email' => 'email@test.com',
            '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 this:

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 19 users.username may not be NULL (SQL: insert into "users" ("updated_at", "created_at") values (2014-03-03 09:57:41, 2014-03-03 09:57:41))

in all tests that involve user creation, as if it had forgotten about the parents attributes when saving the model.

What am I doing wrong?

도움이 되었습니까?

해결책

The problem is that you're overriding what I assume is the Eloquent constructor, so the values are never getting passed.

Change __construct to look like the following.

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

    array_merge ($this->fillable, array(
        'salutation', 'title', 'firstname', 'lastname', 'phonenumber', 'mobilenumber'
    ));
}

The Model::create method will actually create a new instance of the model and pass the array into the __construct. You're overriding this and preventing it from passing the information through.

Note If you decide to override core methods like you've done here, always check inheritance and make sure you aren't breaking anything.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top