【发布时间】:2021-10-09 18:45:58
【问题描述】:
在 Laravel 的视图页面上,我正在显示信息,但视图底部还有一个表单,用户可以在其中留下“评论”。在数据库表中,cmets 的字段最初设置为“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
如果我提交名为“测试”的评论,则 URL 将更改为: /MealPlanDisplay/2?cmets=Test
我对更新(放置)做错了什么感到困惑?非常感谢一些帮助。
【问题讨论】:
-
method= put 不起作用。改用@method('put') 并保持form method=post
-
并且不要使用原始查询。 $plan = MealPlanInput::find($MealPlan_ID); $plan->cmets = $request->cmets;
-
@Maksim
::where('id', '=', $MealPlan_ID)不是“原始”查询,DB::raw('SELECT * FROM meal_plans WHERE id = ' . $MealPlan_ID)是。我同意鼓励使用::find(),但::where('id', $MealPlan_ID)->first()也有效。 @cleocoder,如您在之前删除的问题中所述,停止对单个记录使用->get()。get()返回MealPlanInput实例的集合,但只有 1 会匹配id,因此请使用::find($MealPlan_ID)或::where('id', $MealPlan_ID)->first(); -
@Maksim 是的,Route Model Binding 会自动处理这个问题,但这里没有使用它。不管怎样,就像我说的,我同意使用
::find()。我只是更正::where(...)不是 raw 查询;它仍在使用 Eloquent。
标签: php html laravel model-view-controller