Home » Php » php – Creating a seeder in Laravel 6 that works with foreign key constraint

php – Creating a seeder in Laravel 6 that works with foreign key constraint

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am trying to create a seeder that fills a databases with “Assignments” that are linked with a “Course” database with foreign key constraint.
Since i am pretty new to PHP and Laravel 6 in general i don’t really know where to start.
I allready have a seeder that fills my “Course” database, which like this:

class  CoursesTableSeed extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('courses')->insert([[
            'name' => 'Opleidings- en beroepsoriëntatie',
            'ecs' => '2.5'
        ],[
            'name' => 'Computer science basics',
            'ecs' => '7.5'
        ],[
            'name' => 'Programming basics',
            'ecs' => '5'
        ],[
            'name'=>'Professional skills 1',
            'ecs'=>'2.5',

        ],[
            'name'=>'HZ Personality',
            'ecs'=>'2.5',

        ],[
            'name'=>'Object-oriented programming',
            'ecs'=>'10',

        ],[
            'name'=>'Professional skills 2',
            'ecs'=>'2.5',

        ],[
            'name'=>'Professionele werkplek',
            'ecs'=>'2.5',

        ],[
            'name'=>'Framework development 1',
            'ecs'=>'5',

        ],[
            'name'=>'Framework project 1',
            'ecs'=>'5',

        ],[
            'name'=>'Professional skills 3',
            'ecs'=>'2.5',

        ],[
            'name'=>'IT Personality 1',
            'ecs'=>'2.5',

        ],[
            'name'=>'Framework development 2',
            'ecs'=>'5',

        ],[
            'name'=>'Framework project 2',
            'ecs'=>'5',

        ]
        ]);
    }
}

Now i want to do the same thing with my assignment database but i cant figure out how since i also want to have the “Assignments” linked with theyr respective “Course” so when i delete a course it also deletes it associated assignments. If this question comes over a little vague, sorry for that. I am pretty new to PHP laravel and programming in general.
Also, this is my migration for the assignments:

class CreateAssignmentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('assignments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('course_id');
            $table->text('name');
            $table->decimal('weight',3,1)->nullable();
            $table->decimal('grade', 3, 1)->nullable();
            $table->timestamps();

            $table->foreign('course_id')
                ->references('id')
                ->on('courses')
                ->onDelete('cascade');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('assignments');
    }
}
How to&Answers:

Welcome to Stackoverflow!
You can seed your assignments in different ways. For example: update existing seeder, or create another seeder.

Here code for another seeder (you must have Course and Assignment models):

<?php

use App\Assignment;
use App\Course;
use Illuminate\Database\Seeder;

class AssignmentsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $data = [
            [
                'name' => 'Opleidings- en beroepsoriëntatie',
                'assignments' => [
                    [
                        'name' => 'Assignment 1',
                        'weight' => 1.5,
                        'grade' => 1.1,
                    ],
                    [
                        'name' => 'Assignment 2',
                        'weight' => 2.0,
                        'grade' => 1.2,
                    ],
                ]
            ],
            [
                'name' => 'Computer science basics',
                'assignments' => [
                    [
                        'name' => 'Assignment 3',
                        'weight' => 1.5,
                        'grade' => 1.0,
                    ],
                    [
                        'name' => 'Assignment 4',
                        'weight' => 1.5,
                        'grade' => 1.0,
                    ],
                    [
                        'name' => 'Assignment 5',
                        'weight' => 1.5,
                        'grade' => 1.0,
                    ],
                ]
            ],
        ];

        // Loops through courses
        foreach ($data as $key => $value) {
            $course = Course::where('name', $value['name'])->first();

            if ($course instanceof Course) {
                if (isset($value['assignments']) && is_array($value['assignments'])) {
                    // Loops through assignments
                    foreach ($value['assignments'] as $assignment) {
                        $assignment['course_id'] = $course->id;
                        Assignment::firstOrCreate($assignment);
                    }
                }
            }
        }
    }
}

Put this code to database/seeds/AssignmentsTableSeeder.php file and after that call this console commands:

composer dump-autoload

php artisan db:seed --class=AssignmentsTableSeeder

After that you will get the following result

enter image description here