I have this migration file
class AddRolesFieldsToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->foreignId('role_id')->constrained();
$table->string('student_address')->nullable();
$table->string('student_licence_number')->nullable();
$table->string('teacher_qualifications')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
//
And a User model has all fillables like seen below
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'role_id',
'student_address',
'student_licence_number',
'teacher_qualifications',
];
But I get the SQLSTATE[23000]: Integrity constraint violation 1452 Cannot add or update a child row: a foreign key constraint fails when I try to register a new user, how should I fix this?
To solve this, manually insert the roles value into the database.
So for the first row:
id=2 | name=Teacher | created_at =0000-00-00 00:00:00|updated_at 0000-00-00 00:00:00
Second row:
id=3 | name=Student| created_at =0000-00-00 00:00:00|updated_at 0000-00-00 00:00:00