首页 > 解决方案 > 提交表单数据到数据库

问题描述

我有一个想要添加评论的通用文章模型

Schema::create('article_comments', function (Blueprint $table) {
   $table->BigIncrements('id');
   $table->unsignedBigInteger('article_id');
   $table->foreign('article_id')
      ->references('id')->on('articles')->onDelete('cascade');
   $table->string('name', 128);
   $table->string('email', 128);
   $table->text('text');
   $table->timestamps();

我创建了一个表格,在那里替换了值

<?php

use \App\Models\Article;
    
/**
* @var ArticleBlock $article
*/
?>

<form method="post" action="{{ route('send-comment') }}">
    <div class="row">
        <input type="hidden" name="article_id" value="{{ $article->id }}" />
        <div class="col-md-6">
            <div class="form-item">
                <label for="name">Your Name *</label>
                <div class="input-wrapper">
                    <img src="/img/user.svg" alt="user logo">
                    <input id="name" type="text" name="name">
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-item">
                <label for="email">Your Email *</label>
                <div class="input-wrapper">
                    <img src="/img/mail.svg" alt="mail logo">
                    <input id="email" type="email" name="email">
                </div>
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-item">
                <label for="text">Comment *</label>
                <div class="input-wrapper">
                    <img src="/img/comment-alt.svg" alt="comment-alt logo">
                    <textarea id="text" name="text"></textarea>
                </div>
            </div>
        </div>
    </div>
    <input class="submit-button" type="submit" value="Submit Comment">
</form>

路线

Route::post('send-comment', 'App\Http\Controllers\ArticleController@sendComment')->name('send-comment');

控制器中的功能

public function sendComment(Request $request)
    {
        $articleComment = new ArticleComment;

        $articleComment->name = $request->get('name');
        $articleComment->email = $request->get('email');
        $articleComment->text = $request->get('text');
        $artile = Article::find($request->get('article_id'));
        $article->article_comments()->save($articleComment);

        return back();
    }

但是最后填完表格后,数据没有来,评论也没有创建。当我点击提交按钮时,我得到了这个

419 | 页已过期

可能是什么问题呢?如果您需要更多信息,我随时准备提供

标签: phphtmllaravel

解决方案


您的表单中缺少导致错误的CSRF 令牌

您应该在表单中添加 CSRF 令牌并将其与发布请求一起发送。

在标签中添加@csrf<form>为:

<form method="post" action="{{ route('send-comment') }}">
@csrf
...
</form>

推荐阅读