我是 Laravel 的新手,我一直在努力将数据插入某个表 hods
。该表只有两个字段,一个唯一 id 和一个名为 user_id
的外键。
以下是 Hod
模型的代码:
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Hod extends Model
{
use HasFactory;
protected $table = 'hods';
protected $primaryKey = 'id';
protected $fillable = 'user_id';
}
以下是我希望在其中进行查询的控制器中方法的代码:
public function createHOD(Request $request)
{
// Validate Form Input
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email,except,id',
'password' => 'required|string|min:8|confirmed',
]);
// If Validation Is Successful
if (!$validator->fails()) {
// Create User THIS QUERY WORKS FINE
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => Hash::make($request->input('password')),
'user_type' => "HOD"
]);
// Attaching 'HOD' Role To User
$user->attachRole('HOD');
// Adding The User To The HOD Table NOT WORKING
$hod = new Hod();
$hod->user_id = $user->id;
$hod->save();
// TRIED THIS TOO, ALSO NOT WORKING
DB::table('hods')->insert(
['user_id' => $user->id],
);
return response()->json(['success' => 'HOD Successfully Created.']);
} else {
// Return Error Messages
return response()->json(['error' => $validator->errors()->all()]);
}
}
我正在使用 AJAX
,以下是处理该方面的代码:
$("#hodSubmit").click(function(e) {
e.preventDefault();
var _token = $("input[name=_token]").val();
var name = $("input[name=hod_name]").val();
var email = $("input[name=hod_email]").val();
var password = $("input[name=hod_password]").val();
var password_confirmation = $("input[name=hod_confirmation]").val();
$.ajax({
url: "{{ route('createHOD') }}",
type: 'POST',
data: {
_token: _token,
name: name,
email: email,
password: password,
password_confirmation: password_confirmation
},
success: function(data) {
if ($.isEmptyObject(data.error)) {
$("#hodForm")[0].reset();
printSuccessMsg("hod");
} else {
printErrorMsg(data.error, "hod");
}
}
});
});
如果您需要额外的代码或进一步的解释,请告诉我。谢谢
答案 0 :(得分:1)
将可填充保护更改为数组,如文档所述
protected $fillable = ['user_id'];
更新: 试试其他的
$hod = Hod::create(['user_id' => $user->id]);