php - 我想在用户表中插入一个 ForeignKey,但它在 Laravel 8 中使用 fortify 插入为 null
问题描述
我添加了一个 foreignKey 列来为用户指定一个角色。这是用户表:在我将nullable()添加到role_id列之前,他们被告知role_id列没有默认值,当我添加nullable()时,他们将 NULL 值插入到表中
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('phone_number')->unique();
$table->string('email')->unique()->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->integer('role_id')->unsigned()->nullable();
$table->rememberToken();
$table->timestamps();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
这是角色表:
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('type');
$table->timestamps();
});
这是角色列的刀片代码: 我在刀片上添加了一个数组,以在属性名称为“ role_id ”的选项标签中显示其内容,正如您在刀片代码中看到的那样
@php
$role_array = ['employee', 'client'];
@endphp
<div class="form-group row">
<label for="role" class="col-md-4 col-form-label text-md-right">Role <span class="text-danger">*</span></label>
<div class="col-md-6">
<select id="role" name="role_id" class=" form-control">
<option selected>Choose...</option>
@foreach ($role_array as $x => $x_value)
<option value="{{++$x}}">{{$x_value}}</option>
@endforeach
</select>
</div>
</div>
这是“ CreateNewUser.php ”文件的创建方法:
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => [
'string',
'email',
'max:255',
Rule::unique(User::class),
],
'phone_number' => [
'required',
'string',
'min:10',
'max:13',
Rule::unique(User::class),
],
'role_id' => [
'required',
Rule::unique(User::class),
],
'password' => $this->passwordRules(),
])->validate();
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'phone_number' => $input['phone_number'],
'password' => Hash::make($input['password']),
]);
}
这是用户模型:
protected $fillable = [
'name',
'password',
'phone_number',
'email',
'role_id',
];
解决方案
你必须通过role_id
创建方法
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'phone_number' => $input['phone_number'],
'password' => Hash::make($input['password']),
'role_id' => $input['role_id'],
]);
也适用于控制器中的角色
$role_array=Role::pluck('type','id');
然后在视野中
<select id="role" name="role_id" class=" form-control">
<option selected>Choose...</option>
@foreach ($role_array as $x => $x_value)
<option value="{{$x}}">{{$x_value}}</option>
@endforeach
</select>
推荐阅读
- impala - 从 long | 中提取字段名称值 使用 REGEXP_EXTRACT 在 Cloudera Impala 中分隔字符串
- reactjs - ReactJS,axios - 使用 react-scripts start 命令从本地被 CORS 策略阻止
- azure - 使用 NiFi 从 Azure 到 Google Cloud Platform 的数据流
- tableau-api - Tableau 以行为基数计算百分比
- javascript - 响应未显示 ID 屏幕?
- amazon-web-services - Dynamodb 设计推荐
- haproxy - 即使很少有后端关闭,haproxy 也允许其他后端
- sql - PostgreSQL real type vs double type 查询结果混淆
- javascript - 如何从 .ts 文件中读取 .js 文件中的常量
- algorithm - 新闻源的推荐引擎优化