5

I want to insert foreign key when I will migration than add a foreign key value in 1

`public function up()
    {
        Schema::table('users', function (Blueprint $table) {
      $table->integer('role_id')->unsigned()->after('email')->nullable();
        $table->foreign('role_id')->references('id')->on('roles');
        });
        $data = [
            'name' => 'admin',
            'email' => 'admin@admin.com',
            'role_id' => 1,
            'password' => bcrypt('123456'),
        ];
        App\User::create($data);
    }`

Here is screenshot of the users table

Joshua
  • 40,822
  • 8
  • 72
  • 132
Md Majadul Islam
  • 125
  • 1
  • 11

2 Answers2

4

It is not a good practice to seed data inside Migrations.

Make sure role_id exists in a referenced table.

Also make sure role_id is not gaurded and exist in your fillable array of your User Model.

$fillable = ['role_id']

I would suggest creating a seeder then run the seeder after migration.

php artisan make:seed User

Hope this helps

FULL STACK DEV
  • 15,207
  • 5
  • 46
  • 66
0

create migration set defualt value 1 in foregin key

 $table->integer('role_id')->unsigned()->after('email')->nullable()->default(1);
Ravindra Bhanderi
  • 2,478
  • 4
  • 17
  • 29