首页 > 解决方案 > 在 laravel 和 vuejs 插入数据库 + 日志文件时出现 500 错误

问题描述

我正在尝试使用VueJs将数据存储到我的数据库中,但我不断收到 500 错误
,这是我的代码

export default {
    props: ['post_id','user_id'],
    data: function () {
        return {
            body:'',
            user_name : '',
        }
    },

方法在这里:

methods: {
    loadComments() {
        // axios.get("../api/comment").then(({ data })=>(this.comments - data.data)
        axios.get("../api/comment").then((response) => (this.comments = response.data.data)
            // response => this.comments = response.data
        );
    },
    create() {
        axios.post('../api/comment',{body:this.body});
    },

这是我表格的一部分:

<form @submit.prevent="create()"  id="myForm"  class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed">
    <div class="form-group m-form__group row">
        <div class="col-lg-6">
            <label>name</label>
            <input type="text" placeholder="insert name" name="body" class="form-control m-input" v-model="body">
        </div>

        <div class="col-lg-6">
            <label>email</label>
            <input type="text" placeholder="email" name="title" class="form-control m-input">
        </div>
    </div>

和 api laravel 的路线

Route::resource('comment','CommentController');

最后这是我在 laravel 中得到的日志错误:

[2019-03-25 07:07:08] local.ERROR:SQLSTATE [HY000]:一般错误:1364 字段“body”没有默认值(SQL:插入commentsupdated_atcreated_at)值(2019-03- 25 07:07:08, 2019-03-25 07:07:08)) {"exception":"[object] (Illuminate\Database\QueryException(code: HY000): SQLSTATE[HY000]: General error: 1364 Field 'body' 在 C:\wamp\www 处没有默认值(SQL:插入comments( updated_at, created_at) 值 (2019-03-25 07:07:08, 2019-03-25 07:07:08)) \jabama3\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664, PDOException(code: HY000): SQLSTATE[HY000]: General error: 1364 Field 'body' does not have a default value at C :\wamp\www\jabama3\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458)

我知道我的表单没有发送数据,而 laravel 需要数据,但我不知道我做错了哪一部分。

编辑这里是我的商店方法:

 public function store(Request $request)
{
    Comment::create($request->all());
    return (['message' => 'succes']);
}

这是我的表结构:

 Schema::create('comments', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->longText('body');
        $table->integer('user_id')->nullable();
        $table->string('user_email')->nullable();
        $table->string('user_name');
        $table->integer('status')->default('0');
        $table->integer('post_id');
        $table->timestamps();
    });

标签: phplaravelvue.js

解决方案


这是因为当您向表中插入数据时,您的主体是空的。原因是您正在使用 Create 方法来插入数据。并且 Create 方法需要protected $fillable = ['field1','field2',...]在模型中包含表字段的数组。将 $fillable 添加到您的模型中。您可以点击此链接以获取有关批量分配的更多信息


推荐阅读