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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With