我正在尝试创建一个多步骤表单供用户在登录后填写。我创建了单独的页面,其中包含将成为通用表单的一部分的表单。
数据将保存在“用户”表中。
我是 Laravel 的新手,我遵循了这个:https ://www.5balloons.info/multi-page-step-form-in-laravel-with-validation/
在我的 FormController 我有这些方法:
public function index(Request $request)
{
$request->session()->forget('user');
$user = User::all();
return view('form.index',compact('user',$user));
}
public function updateStep1(Request $request)
{
$user = $request->session()->get('user');
return view('form.update-step1',compact('user', $user));
}
public function postupdateStep1(Request $request)
{
$validatedData = $request->validate([
'first_name' => 'required',
]);
if(empty($request->session()->get('user'))){
$user = User::where('id',auth()->user()->id)->first();
$user->fill($validatedData);
$request->session()->put('user', $user);
}else{
$user = $request->session()->get('user');
$user->fill($validatedData);
$request->session()->put('user', $user);
}
return redirect('/form/update-step2');
}
public function updateStep2(Request $request)
{
$user = $request->session()->get('user');
return view('form.update-step2',compact('user', $user));
}
public function postupdateStep2(Request $request)
{
$validatedData = $request->validate([
'address' => 'required',
]);
if(empty($request->session()->get('user'))){
$user = User::where('id',auth()->user()->id)->first();
$user->fill($validatedData);
$request->session()->put('user', $user);
}else{
$user = $request->session()->get('user');
$user->fill($validatedData);
$request->session()->put('user', $user);
}
return redirect('/form/store');
}
public function store(Request $request)
{
$user = User::where('id',auth()->user()->id)->first();
$user = $request->session()->get('user');
$user->save();
return redirect('/form');
}
这些是路线:
Route::get('/form', 'FormController@index');
Route::get('/form/update-step1', 'FormController@updateStep1');
Route::post('/form/update-step1', 'FormController@postupdateStep1');
Route::get('/form/update-step2', 'FormController@updateStep2');
Route::post('/form/update-step2', 'FormController@postupdateStep2');
Route::post('/form/store', 'FormController@store');
这是表格的第一部分:
@extends('layouts.app')
@section('content')
<h1>update - Step 1</h1>
<form action="/form/update-step1" method="post">
@csrf
<div class="form-group">
<label for="name">First Name</label>
<input type="text" value="{{ old('first_name', $user->first_name ?? null) }}" class="form-control" name="name">
</div>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<button type="submit" class="btn btn-primary">Continue</button>
</form>
@endsection
当我尝试提交时,我收到一个错误,说这些字段是必需的。因此,即使我确实输入了名称等,它也不起作用。如果我删除验证,似乎一切正常,但没有数据添加到数据库中。
有什么建议么?