【问题标题】:Laravel why record is not updating using vuejsLaravel 为什么不使用 vuejs 更新记录
【发布时间】:2022-01-03 13:58:34
【问题描述】:

我在向 Laravel 控制器发送请求时尝试更新文本,但出现错误:

500 internal server error 
Uncaught (in promise) Error: Request failed with status code 500

console.log 正在显示我试图发送给控制器的文本和值:

id:16 text:aa

vue js 代码:

const onEdit=(todo)=>{
    //  var src = evt.target.innerHTML
    //  this.txt = src
    axios
        .put('http://127.0.0.1:8000/api/todo/update', {
            id:todo.id,
            text:todo.text
        })
        .then(() => getTodos());

    console.log("working", todo.text, todo.id);
};

Laravel 控制器:

public function updateData(Request $request)
{
    $todo = Todo::find($request->id);
    $todo->update($request->all());

    return response()->json([
        'message' => 'updated'
    ]);
}

路线:

Route::put('todo/update',[TodoController::class,'updateData']);

型号:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Todo extends Model
{
    use HasFactory;
    protected $dates = [
        'created_at',
        'updated_at',
        
    ];

    protected $fillable = ['id'];
}

更新:

我检查了 laravel 日志,我得到了错误:

Add [id] to fillable property to allow mass assignment on [App\Models\Todo]. 

然后我在模型中添加了 id。现在我在控制台日志中看到以下响应,但它没有更新数据。

【问题讨论】:

  • 尝试 $todo->update(['text'=>$request->text]);而不是 $todo->update($request->all());
  • 记录不更新使用它
  • 你能显示 Todo 型号代码吗
  • 删除可填充属性保护 $fillable = ['id'];并添加受保护的 $guarded=['id'];
  • 尝试所有()它应该可以工作

标签: laravel vue.js laravel-8 vuejs3


【解决方案1】:

问题在于 Todo 模型,您允许 id 字段为可填写。由于 id 是数据库中的自动增量字段。所以文本字段应该是可填写的。

  protected $fillable = ['id'];

所以在这里你有两个选择。一个是允许$fillable 属性到text 字段或保护 id 属性,所以所有其他属性都是填充

所以

 protected $guarded=['id'];

protected $fillable=['text'];

【讨论】:

  • 谢谢你,冠军!
【解决方案2】:

500 错误是一般的服务器端错误。

首先,编辑您的 onEdit 函数以添加 catch,以便您可以通过控制台记录服务器错误。

const onEdit = (todo) => {
  axios.put('http://127.0.0.1:8000/api/todo/update', {
    id: todo.id,
    text: todo.text
  }).then(response => {
    console.log(response)
    getTodos()
  }).catch(error => {
    console.log(error)
  })
}; 

一旦您知道服务器错误是什么,您就会知道要修复什么。

【讨论】:

  • 下添加了sn-p
  • 好吧,这没有任何帮助。你也需要检查你的 Laravel 日志。
  • 更新问题。
  • 现在数据没有更新 - 这意味着您的 getTodos() 函数可能无法正常工作。如果您控制台记录来自 getTodos 的响应数据,它是否包含您更新的待办事项?
  • 我在 sql 中也看不到更新的数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多