laravel - 无法将数据持久化到数据库?(拉拉维尔)
问题描述
我是 Laravel 的新手。我的数据似乎没有进入数据库。这是我的控制器代码:
public function store(Request $request)
{
$rules = [
'first_name' => 'required|string|min:3|max:255',
'last_name' => 'required|string|min:3|max:255',
'gender' => 'required|string|min:3|max:255',
'qualifications' => 'required|string|min:3|max:255'
];
$validator = FacadesValidator::make($request->all(), $rules);
if ($validator->fails()) {
return redirect('/home')
->withInput()
->withErrors($validator);
} else{
$data = $request->input();
try {
$crud = new CRUD;
$crud->first_name = $request->get('first_name');
$crud->last_name = $request->get('last_name');
$crud->gender = $request->get('gender');
$crud->qualifications = $request->get('qualifications');
$crud->save();
return redirect('/home')->with('status',"Insert successfully");
} catch (\Throwable $th) {
return redirect('/home')->with('failed',"Insert Failed");
}
}
}
我的模型:
protected $table = '$user';
protected $fillable = [
'first_name', 'last_name', 'gender', 'qualifications'
];
public $timestamps = true;
我的路线(Web.php):
Route::post('/store', [App\Http\Controllers\CRUDController::class, 'store'])->name('insert');
这是我的迁移users table
:
Schema::create('user', function(Blueprint $table) {
$table->bigIncrements('id');
$table->string('first_name');
$table->string('last_name');
$table->string('gender');
$table->string('qualifications');
$table->timestamps();
});
解决方案
您应该在模型中修复您的表名,因为您的表被称为user
:
protected $table = "user";
此外,您可以使用质量分配来填充模型:
$crud = CRUD::create($request->validated());
它应该可以解决您的问题。
推荐阅读
- javascript - 来自移动浏览器的角度上传图像不起作用
- python - 带有 docker 的烧瓶在除 root 之外的所有路由上返回 404
- javascript - JavaScript 类型编写器效果从 onclick 更改为 onload
- javascript - 如何在文本区域中显示来自服务器的数据
- javascript - 在Vue Js的表格中创建奇数和偶数单元格的问题
- python - 排列numpy数组
- c++ - 如何在向量队列或向量向量上使用 std::async 进行排序?
- java - 快速排序稳定性演示
- ffmpeg - 如何在混合视频流时设置 sample_aspect_ratio?
- laravel - Laravel 我可以在资源控制器上添加两个更新方法吗