Laravel:更新一个值保持值为空?



在Laravel的视图页面上,我正在显示信息,但我在视图底部也有一个表单,用户可以在其中留下"评论"。在数据库表中,用于评论的字段最初设置为'null',然后如果用户决定提交评论,它将更新该字段。

代码运行,但它似乎不工作,当我检查数据库的值仍然为空吗?

控制器(更新函数):

public function update(Request $request, $MealPlan_ID) {
$comments = $request->comments;
$commentupdate = MealPlanInput::where('id', '=', $MealPlan_ID)->update(['comments' => $comments]);
$data = MealPlanInput::where('id', '=', $MealPlan_ID)->get();
return view('MealPlanDisplay.modal', compact('data', 'MealPlan_ID'));

控制器(show)函数,当我没有它时抛出错误):

public function show($MealPlan_ID) {
$data = MealPlanInput::where('id', '=', $MealPlan_ID)->get();
return view('MealPlanDisplay.modal', compact('data','MealPlan_ID'));
}

窗体:

<form method="put" action="{{ route('MealPlanDisplay.update', $MealPlan_ID) }}">
<div class="shadow overflow-hidden sm:rounded-md">
<div class="px-4 py-5 bg-white sm:p-6">
<label for="comments" class="block font-medium text-sm text-gray-700">Personal Comments about Meal Plan</label>
<input type="text" name="comments" id="comments" type="text" class="form-input rounded-md shadow-sm mt-1 block w-full"
value="{{ old('comments', '') }}" />
@error('comments')
<p class="text-sm text-red-600">{{ $message }}</p>
@enderror
</div>
<div class="flex items-center justify-end px-4 py-3 bg-gray-50 text-right sm:px-6">
<button class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase">
Submit Comment
</button>

路线:

//the /view and then the relevant ID of the information being displayed
Route::put('/MealPlanDisplay/modal/{MealPlan_ID}', [MealPlanDisplayController::class, 'update']);

我注意到的一件事是,URL在提交后会改变,所以当URL正常时:/MealPlanDisplay/2

如果我提交一个名为"Test"的评论,URL将变为:/MealPlanDisplay/2 ?评论=测试

我很困惑,我做错了什么更新(放)?如果你能帮忙,我将非常感激。

为了便于理解,我将@nice_dev注释转移到您的代码中。我还包括@csrf语句,它添加了csrf令牌,您通常希望在post请求中使用它。(否则你可能会得到一些错误)

<form method="post" action="{{ route('MealPlanDisplay.update', $MealPlan_ID) }}">
@method('PUT')
@csrf
//.... the rest

为什么你需要使用POST而不是PUT?
PUT未被识别为有效方法,因此将get请求发送到后端并调用错误的控制器方法。

最新更新