Laravel 为什么记录没有使用 vuejs 更新

Laravel why record is not updating using vuejs

我试图在向 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。现在我在控制台日志中看到以下响应,但它没有更新数据。

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)
  })
}; 

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

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

  protected $fillable = ['id'];

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

所以

 protected $guarded=['id'];

protected $fillable=['text'];