Laravel:更新值会使值保持为空?

Laravel: Updating a value keeps value as null?

在 Laravel 的视图页面上,我正在显示信息,但在视图底部还有一个表单,用户可以在其中留下 'comment'。在数据库 table 中,评论字段最初设置为 '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'));

Controller(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?comments=测试

我对更新(放置)做错了什么感到困惑?非常感谢您的帮助。

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

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

为什么需要使用 POST 而不是 PUT?
PUT 未被识别为有效方法,因此向您的后端发送了一个获取请求并调用了错误的控制器方法。