You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何更新数据库数据?附自写代码求指导

Laravel 数据库数据更新问题修正

原代码存在的问题

控制器代码问题

  1. 验证规则矛盾:title和description同时设置了string和integer规则,二者互斥会导致验证失败
  2. 更新逻辑错误:使用$post->create($validatedRequests)是创建新记录,而非更新已有数据
  3. 重定向URL语法错误:PHP字符串中不能使用Blade模板的{{}}语法,需直接拼接变量
  4. price的验证规则末尾多了一个无效的|

视图代码问题

  • 描述字段的label标签for属性拼写错误:decsription应为description

修正后的代码

控制器代码

public function edit($id){
    $post = Posts::find($id);

    return view('edit', compact('post'));
}

public function update(Request $request, $id){
    $post = Posts::findOrFail($id); // 改用findOrFail,找不到记录时直接抛出404
            
    $validatedRequests = $request->validate([
        'title' => 'required|max:255|string',
        'description' => 'required|max:255|string',
        'price' => 'required|integer|max:255'
    ]);

    // 更新已有记录
    $post->update($validatedRequests);
            
    return redirect("/post/{$post->id}")->with('mssg', '更新成功');
}

路由代码(无需修改)

Route::get('/post/{id}/edit', [PostController::class, 'edit']);
Route::put('/post/{id}/update', [PostController::class, 'update']);

视图代码

<form method="POST" action="/post/{{$post->id}}/update">
    @csrf
    @method('PUT')
    <label class="underline" for="title">修改标题:</label></br>
    <input type="text" name="title" value="{{$post->title}}"></input></br>
    <label class="underline" for="description">修改描述:</label></br>
    <input type="text" name="description" value="{{$post->description}}"></input></br>
    <label class="underline" for="price">修改价格:</label></br>
    <input type="text" name="price" value="{{$post->price}}"></input></br>

    <input type="submit" value="提交">
</form>

内容的提问来源于stack exchange,提问作者lolich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 21:10:29