Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert foreign key value laravel with migration in laravel

Tags:

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' => '[email protected]',
            'role_id' => 1,
            'password' => bcrypt('123456'),
        ];
        App\User::create($data);
    }`

Here is screenshot of the users table

like image 673
Md Majadul Islam Avatar asked Mar 02 '18 04:03

Md Majadul Islam


1 Answers

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

like image 62
Romantic Dev Avatar answered Sep 20 '22 12:09

Romantic Dev