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

littleboby's avatar

Illuminate\Database\QueryException : SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

Creating an application where people create events or 'meetups'. I created my factories: 2019_06_20162119_create_groups_table, (different meetup categories) 201906_20_170900create_meetups_table, (the events themselves) 201906_20182232_create_attending_table, (people that are attending) & 201906_20_182319_create_group_members_table (members of the different categories)

After I created the seeders and factories and doing php artisan db:seed the error comes up, here's what my scripts look like(sorry for the long post):

Meetups table:

class CreateMeetupsTable extends Migration
{
   /**
    * Run the migrations.
    *
    * @return void
    */
   public function up()
   {
       Schema::create('meetups', function (Blueprint $table) {
           $table->bigIncrements('id');
           $table->string('title');
           $table->longText('description');
           $table->string('place');
           $table->dateTimeTz('time_happening');
           $table->timestamps();
           $table->bigInteger('created_by')->unsigned();
           $table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
           $table->bigInteger('group_id')->unsigned();
           $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');
       });
   }

   /**
    * Reverse the migrations.
    *
    * @return void
    */
   public function down()
   {
       Schema::dropIfExists('meetups');
   }
}

Groups table:

class CreateGroupsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('groups', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('description');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('groups');
    }
}

Attending table:

class CreateAttendingTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('attending', function (Blueprint $table) {
            $table->bigInteger('meetup_id')->unsigned();
            $table->foreign('meetup_id')->references('id')->on('meetups')->onDelete('cascade');
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('attending');
    }
}

Group members table:

class CreateGroupMembersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('group_members', function (Blueprint $table) {
            $table->bigInteger('group_id')->unsigned();
            $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('group_members');
    }
}

MeetupsTableSeeder:

class MeetupsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Meetup::class, 100)->create();
    }
}

AttendingTableSeeder:

class AttendingTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Attending::class, 100)->create();
    }
}

GroupMembersSeeder

class GroupMembersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\GroupMembers::class, 500)->create();
    }
}

UserTableSeeder:

public function run()
    {
        factory(App\User::class, 50)->create();
    }

& DatabaseSeeder

public function run()
    {
        $this->call(MeetupsTableSeeder::class);
        $this->call(UserTableSeeder::class);
        $this->call(AttendingTableSeeder::class);
        $this->call(GroupMembersSeederTableSeeder::class);
    }

The meetups factory looks like this:

$factory->define(App\Meetup::class, function (Faker $faker) {
    return [
        'title' => $faker->text(30),
        'description' => $faker->text(200),
        'place' => $faker->streetAddress(),
        'created_by' => rand(1, 50),
        'group_id' => rand(1, 15),
        'time_happening' =>$faker->dateTime($max = 'now', $timezone = null)
    ];
});

Group members factory:

$factory->define(App\GroupMembers::class, function (Faker $faker) {
    return [
        'group_id' => rand(1, 15),
        'user_id' => rand(1, 50)
    ];
});

Attending factory:

$factory->define(App\Attending::class, function (Faker $faker) {
    return [
        'meetup_id' => rand(1, 100),
        'user_id' => rand(1, 50)
    ];
});

& the Users factory:

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => bcrypt('secret'), // secret
        'remember_token' => Str::random(10),
    ];
});

I also created the models for every table/class but have written nothing in them as yet, I am aware that there are a lot of questions like this on other platforms but none of the answers seem to help with my case, so in advance thank you kind stranger/s!

0 likes
10 replies
Nakov's avatar

You cannot use a random number as a foreign key, the relationship must exist in order to relate to it, so I will give you an example just for your MeetupSeeder, you can change the rest:

use App\User;
use App\Group;

$factory->define(App\Meetup::class, function (Faker $faker) {
    return [
        'title' => $faker->text(30),
        'description' => $faker->text(200),
        'place' => $faker->streetAddress(),
        'created_by' => factory(User::class),
        'group_id' => factory(Group::class),
        'time_happening' =>$faker->dateTime($max = 'now', $timezone = null)
    ];
});

This will also create a user and associate it with the meetup, and a group which will also be associated with this meetup.

littleboby's avatar

@NAKOV - Thanks for the reply, does this generate a random Existing user_id for each meetup?! Trying this now

Nakov's avatar
Nakov
Best Answer
Level 73

@LITTLEBOBY - No it will not be an existing one, but it will create and persist a new one, and it will associate it with it. If you want to make a relationship to an existing one, you can do the following:

$user = factory(User::class)->create();

factory(Meetup::class, 50)->create(['created_by' => $user->id]);

This way all the meetups will be to one user only.

littleboby's avatar

@NAKOV - Okay now my factory looks like this:

$factory->define(App\Meetup::class, function (Faker $faker) {

    $user = factory(User::class)->create();

    return [
        'title' => $faker->text(30),
        'description' => $faker->text(200),
        'place' => $faker->streetAddress(),
        'created_by' => factory(Meetup::class, 100)->create(['created_by' => $user->id]),
        'group_id' => factory(Group::class),
        'time_happening' =>$faker->dateTime($max = 'now', $timezone = null)
    ];
});

and I'm getting Symfony\Component\Debug\Exception\FatalThrowableError : Class 'User' not found in the console, did I do something wrong?!

Nakov's avatar

@LITTLEBOBY - You should follow my code. Your code now does not make sense.

// this will never work.
'created_by' => factory(Meetup::class, 100)->create(['created_by' => $user->id]),

The lines that I gave you above should be in your seeder, not in the factory.

You forgot to import the User that's why you have the error, so either use :

$user = factory(App\User::class)->create();

or put

use App\User;

above the $factory definition.

littleboby's avatar

@NAKOV - I oversaw you adding the classes at the top, my bad. The factory seems to be working now, however there is this Illuminate\Database\QueryException : SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`styx-occursum`.`meetups`, CONSTRAINT `meetups_group_id_foreign` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`) ON DELETE CASCADE) (SQL: insert into `meetups` (`title`, `description`, `place`, `created_by`, `group_id`, `time_happening`, `updated_at`, `created_at`) values (Et quos ut velit aut., Odit voluptas est veniam eum et asperiores et. Iste quia et voluptas est. Eligendi maxime saepe provident neque. Neque quia voluptatibus eum quisquam. Sapiente culpa neque earum molestiae aut in., 26588 Glover Route Apt. 552, 104, 4, 2015-11-13 04:56:36, 2019-06-20 21:41:27, 2019-06-20 21:41:27)) error not letting it work now

Nakov's avatar

@LITTLEBOBY - As I said, you have to change your other factories, not to use random numbers for their relationships, but to also use a factory to create and persist a new record. The record must exist in order to add a relation. So change all your factories based on the first one that I gave you.

I hope I am clear.

Nakov's avatar

@LITTLEBOBY - Happy to help. Please mark the answer above as the Best Answer so it might help someone else looking for the same issue.

munazzil's avatar

You have to keep both id as same bigInteger otherwise foreign key not created and you have to run accordingly database tables,

 $table->bigInteger('id');
 $table->bigInteger('group_id')->unsigned();

Please or to participate in this conversation.