Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jrdavidson's avatar

Seeding Issue

I'm trying to seed my database and it gets down to the NewsArticlesTableSeeder and it fails due to it not being able to place a value in for the poster_id as the error indicates however I'm trying to find out why this is.

Inside the NewsArticlesTableSeeder I dd() on the userIds and I keep getting an empty array and I don't know why that is if I'm getting that Seeded message saying it works on the Users table.

Me-iMac:manager me$ php artisan db:seed
Seeded: UserRolesTableSeeder
Seeded: UserStatusesTableSeeder
Seeded: UsersTableSeeder
Seeded: UserProfilesTableSeeder
Seeded: NewsCategoriesTableSeeder

  [Illuminate\Database\QueryException]
  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'poster_id' cannot be null (SQL: insert into `news_articles` (`poster_id`, `date_posted`, `title`, `content`, `news_category_id`, `visible`, `updated_at`, `created_at`) values (, 2014-11-17 20:12:54, Ut illo omnis sed natus minima., Quis aliquam dolorem q
  uaerat tenetur animi sequi. Dolorem ab molestiae sed non iusto consequuntur dolores adipisci. Nulla eum sequi recusandae atque tenetur cupiditate quo. Iste deserunt eius alias dolor et omnis.
  Sed laborum rerum eaque aut. Ipsa laboriosam ipsam eveniet qui odit. Dignissimos non ea aut quasi. Et modi in quis.
  Voluptatibus dignissimos enim minus temporibus sed vero rerum eos. Et numquam suscipit sapiente debitis. Ipsa totam necessitatibus beatae aut illum impedit.
  Modi dolor nam quia eos. Qui esse maiores voluptas sint. In ratione soluta sed incidunt. Temporibus labore et facilis animi autem. Voluptas ipsa minus animi quidem.
  Velit nihil ut et id molestias eaque. Quo esse et nihil labore aspernatur. Commodi eius dicta velit soluta voluptas.
  Accusantium dolores omnis repellat minima. Voluptas recusandae eveniet quibusdam expedita ipsa. Dolor perspiciatis qui nihil voluptatem nam eaque rerum.
  Facere vero illum quas. Totam consequatur voluptatem quam nihil qui., 7, yes, 2014-11-12 22:20:02, 2014-11-12 22:20:02))

  [PDOException]
  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'poster_id' cannot be null

db:seed [--class[="..."]] [--database[="..."]] [--force]

<?php

// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;

class NewsArticlesTableSeeder extends Seeder {

 public function run()
 {
    $faker = Faker::create();

    $userIds = User::lists('id');
    dd($userIds);
    $categoryIds = NewsCategory::lists('id');

    foreach(range(1, 10) as $index)
    {
   NewsArticle::create([
    'poster_id' => $faker->randomElement($userIds),
    'date_posted' => $faker->dateTimeBetween('now', '+7 days'),
    'title' => $faker->text(50),
    'content' => $faker->text(1000),
    'news_category_id' => $faker->randomElement($categoryIds),
    'visible' => $faker->randomElement(array('yes', 'no')),
   ]);
    }
 }
}
0 likes
55 replies
jrdavidson's avatar

After doing some testing I found out that with the User model when I have it extend Eloquent it works but if I have it extend BaseModel which extends Eloquent then it doesn't work. What is the reason for this?

austenc's avatar

Are you specifying a constructor in User or BaseModel? post us the code for those models maybe?

jrdavidson's avatar

Oh wow I'm not. That would be why. What constructors should I be doing in those?

austenc's avatar

You don't need to, but I just wanted to make sure they were correct if so. Have you confirmed that there are records inserted into the table by the UserSeeder?

jrdavidson's avatar

Well I added the constructors which now its kind of in working condition however when I go to run a seeder I get this error message.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'users_username_unique'
<?php

// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;

class UsersTableSeeder extends Seeder {

    public function run()
    {    
        User::create([
            'first_name' => 'First',
            'last_name' => 'Last',
            'username' => 'myusername',
            'email_address' => 'myemail@gmail.com',
            'avatar' => 'Myava',
            'password' => Hash::make('changeme'),
            'role_id' => 4,
            'status_id' => 1
        ]);

        //create instanances for each fake user
        $faker = Faker::create();

        $roleIds = UserRole::lists('id');
        $statusIds = UserStatus::lists('id');

        foreach(range(1, 20) as $index)
        {
            User::create([
                'first_name' => $faker->firstName,
                'last_name' => $faker->lastName,
                'username' => $faker->username,
                'email_address' => $faker->freeEmail,
                'avatar' => $faker->lexify('????????'),
                'password' => Hash::make($faker->word),
                'role_id' => $faker->randomElement($roleIds),
                'status_id' => $faker->randomElement($statusIds)
            ]);
        }
    }

}
austenc's avatar

@xtremer360 if you don't need to define the constructors, there's no reason to have them. I was just asking if you had them on the overridden classes or not to help myself further diagnose the issue.

jrdavidson's avatar

Well that took care of that issue but now its not putting in these values for the UserSeeder

austenc's avatar

Try removing the constructors from BaseModel and User to take us back to the original issue. Does the users table have records? (I know the seeder runs, but when you look at the table, confirm it has records)

jrdavidson's avatar

When I run the seeder it gives me the error message about the poster_id from the beginning.

<?php

class User extends BaseModel implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait, SoftDeletingTrait;

    protected $fillable = ['first_name', 'last_name', 'username', 'avatar', 'role_id', 'status_id', 'email_address', 'password'];

    protected static $rules = [
        'first_name' => 'required',
        'last_name' => 'required',
        'username' => 'required|unique:users',
        'email_address' => 'required|email|unique:users',
        'avatar' => 'required|unique:users',
        'password' => 'required|confirmed',
        'role_id' => 'required',
        'status_id' => 'required'
    ];
}
<?php

class BaseModel extends Eloquent {

    protected $errors;

    public static function boot()
    {
        parent::boot();

        static::saving(function($model)
        {
            return $model->validate();
        });
    }

    public function validate()
    {
        $validation = Validator::make($this->getAttributes(), static::$rules);

        if ($validation->fails())
        {
            $this->errors = $validation->messages();

            return false;
        }

        return true;
    }

    public function getErrors()
    {
        return $this->errors;
    }
}
austenc's avatar

How many records are you seeing in your users table? All 20 or so? Seems like maybe the user seeder didn't quite work as expected... especially if this gives an empty array:

User::lists('id');
jrdavidson's avatar

It's only doing one row with empty strings as the values.

jrdavidson's avatar

This is using the constructs though. So I'm getting somewhere.

austenc's avatar

There's no point to having those if you don't need them... Does it function the same without the constructors? Or does it seed the users table with all the records as expected?

If you insist on using a constructor (which is likely not doing much for you...) make sure that they match eloquent's constructor parameters, and that they call parent::__construct()

jrdavidson's avatar
<?php

class BaseModel extends Eloquent {

    protected $errors;

    public function __construct()
    {
        parent::__construct();
    }

    public static function boot()
    {
        parent::boot();

        static::saving(function($model)
        {
            return $model->validate();
        });
    }

    public function validate()
    {
        $validation = Validator::make($this->getAttributes(), static::$rules);

        if ($validation->fails())
        {
            $this->errors = $validation->messages();

            return false;
        }

        return true;
    }

    public function getErrors()
    {
        return $this->errors;
    }
}
<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends BaseModel implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait, SoftDeletingTrait;

    protected $fillable = ['first_name', 'last_name', 'username', 'avatar', 'role_id', 'status_id', 'email_address', 'password'];

    protected static $rules = [
        'first_name' => 'required',
        'last_name' => 'required',
        'username' => 'required|unique:users',
        'email_address' => 'required|email|unique:users',
        'avatar' => 'required|unique:users',
        'password' => 'required|confirmed',
        'role_id' => 'required',
        'status_id' => 'required'
    ];

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

    /**
     * Get the user's full name by concatenating the first and last names
     *
     * @return string
     */
    public function getFullName()
    {
        return $this->first_name . ' ' . $this->last_name;
    }

    public function role()
    {
        return $this->hasOne('UserRole', 'id', 'role_id');
    }

    public function profile()
    {
        return $this->hasOne('UserProfile');
    }

    public function status()
    {
        return $this->hasOne('UserStatus', 'id', 'status_id');
    }

}

austenc's avatar

constuctors extending eloquent need to have the same method signature, so in your case

public function __construct($attributes = array())

The point I'm trying to get across to you is that even if you do have those, since you're not doing anything else inside the constructor(s), it's the exact same as not listing them in your two classes there. The problem seems to be your UserTableSeeder isn't inserting the records you're expecting in either case.

jrdavidson's avatar

Correct. I don't know what is preventing it from working as when I have the User model extend Eloquent then it works but if I extend the BaseModel then it doesn't.

austenc's avatar

So to be clear, in that case (User extending Eloquent) the users table has the records you'd expect from the seeder?

Put the constructor on just the User model, does that fix the issue?

class User extends BaseModel {

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

}
jrdavidson's avatar

Unfortunately it still does the same. I'm still getting the following issue. Its still not getting anything in the users table. The below part is coming from the NewsArticlesTableSeeder.

Mine-iMac:manager mine$ php artisan db:seed
Seeded: UserRolesTableSeeder
Seeded: UserStatusesTableSeeder
Seeded: UsersTableSeeder
Seeded: NewsCategoriesTableSeeder



  [Illuminate\Database\QueryException]
  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'poster_id' cannot be null (SQL: insert into `news_articles` (`poster_id`, `date_posted`, `title`, `content`, `news_category_id`, `visible`, `updated_at`, `created_at`) values (, 2014-11-13 20:37:55, Unde aut qui ab maxime enim asperiores., Et omnis autem
   mollitia debitis quibusdam. Rerum amet ea dolores id. Illum quod sit voluptatem inventore explicabo. Sed delectus commodi ut vitae cumque animi.
  Hic sint et eius quo aut quo omnis. Deleniti quo ea rerum consequatur aut et qui dolorem. Expedita quia debitis laboriosam rerum.
  Modi atque eveniet placeat dolorem. Optio ut maxime voluptate. Ut facere ea sit hic.
  At excepturi accusamus omnis dolor neque impedit a. Ut est voluptas quasi laboriosam autem et sint praesentium. Et soluta eligendi pariatur dolor similique sunt molestias.
  Necessitatibus beatae iste eum nihil corporis tenetur. Repellat fuga inventore facilis suscipit consectetur inventore nemo. Eos quia dignissimos quia quod minima voluptatem aut nisi.
  Voluptas dolores vel quae error saepe dolores omnis. Voluptas ducimus sed facere dolor laudantium. Cumque at excepturi doloribus ullam quia aut magni.
  Sapiente ipsam accusantium debitis et officia. Eius perferendis qui amet similique., 7, yes, 2014-11-13 01:12:40, 2014-11-13 01:12:40))






  [PDOException]
  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'poster_id' cannot be null



db:seed [--class[="..."]] [--database[="..."]] [--force]
uxweb's avatar

Seems like at the point this seeder runs there are no records in the users table.

Please, assert that you have user records when this seeder is executing

jrdavidson's avatar

There is not. Please review the full post to understand what is happening.

uxweb's avatar

All your models should extend Eloquent class but not BaseModel, unless you have some logic in BaseModel needed in the extending classes.

uxweb's avatar

Maybe the validator that you build up into the base model is not letting the seeder to create any record in the users table, maybe some data generated by the seeder doesn't meet with the validation rules.

uxweb's avatar

Try not extending the User model from BaseModel, extend it from Eloquent an run the seeders, maybe this can help you to guess if the validation is the problem. :)

1 like
jrdavidson's avatar

Well when I do that then it does run the seeder successfully. What can I do to find out what is happening to prevent passes validation.

uxweb's avatar

Make sure the faker is generating data according to your validation rules.

jrdavidson's avatar

I really don't think it has anything to do with faker because as I've said numerous times now it works when I extend the User model from Eloquent but if I turn it into extending BaseModel the. It doesn't.

uxweb's avatar

Yeah, it works because there is no built in validation in your models.

I'm not gonna say if that method is a good or bad approach to validate data entering your models, but if you are going to use it at least must understand how it works and why using it can cause you this kind of issues.

jrdavidson's avatar

So from your comment you don't have any more ideas?

Next

Please or to participate in this conversation.