Elihai David Vanunu
Elihai David Vanunu

Reputation: 163

Laravel seeder raise 'Column not found' about dummy column

I have a User model with custom attribute, attribute name that concatenate firstName and lastName:

class User extends Authenticatable
{
    /**
     * @var array
     */
    protected $fillable = ['firstName', 'lastName'];

    protected $appends = [
        'name'
    ];

    public function getNameAttribute(){
        return $this->attributes['firstName'] . ' ' . $this->attributes['lastName'];
    }
}

Also I have a many to many relation to Group model.

The problem is, when I try to do seeding:

factory(App\Group::class, 30)
    ->create()
    ->each(function ($group) {
        $group->users()->createMany(factory(App\User::class, 3)->make()->toArray());
    });

I get exception:

 SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name' in 'field list'

My Factory:


$factory->define(User::class, function (Faker $faker) {

    return [
        'firstName' => $faker->firstName,
        'lastName' => $faker->lastName,
   ];
});

When I comment name attribute, it works fine. Thanks.

Upvotes: 0

Views: 514

Answers (1)

lagbox
lagbox

Reputation: 50491

Don't convert the collection of Users to an array. This serializes the models and in your case you are appending the name attribute which is an accessor and doesn't exist.

When it comes to seeding your models are unguarded already so fillable/guarded isn't in play.

Since you have model instances (that have not been saved yet) that you want to add to the relationship you should be using saveMany instead of createMany.

$group->users()->saveMany(factory(App\User::class, 3)->make());

This way you are not serializing the model to an array which would add the name field which you don't want to try and save since that field is 'virtual'.

Though I am not entirely sure how you setup this relationship.

Upvotes: 2

Related Questions