首页 > 解决方案 > 无法将数据持久化到数据库?(拉拉维尔)

问题描述

我是 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();
});

标签: laravel

解决方案


您应该在模型中修复您的表名,因为您的表被称为user

protected $table = "user";

此外,您可以使用质量分配来填充模型:

$crud = CRUD::create($request->validated());

它应该可以解决您的问题。


推荐阅读