【问题标题】:Error 500 (Internal Server Error) ajax and laravel错误 500(内部服务器错误)ajax 和 laravel
【发布时间】:2017-11-05 03:55:36
【问题描述】:

大家好,我在 laravel 和 ajax 中的 cmets 系统遇到问题。实际上它只适用于 php,但我遇到了 ajax 问题。

这是错误信息:

状态代码:500 内部服务器错误。错误提示:1/3 SQLSTATE[23000]:Integrity constraint violation:1048 Column 'post_id' cannot be null。

我正在以模态方式编辑 cmets,我可以创建新评论,但问题是使用 ajax 进行编辑。

JS代码:

<script>

  var commentId = 0;
        var divcomment = null;

        $('.edit-comment').click(function(event){
          event.preventDefault();
          var divcomment = this.parentNode.parentNode;
          commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
          var commentBody = $(divcomment).find('#display-comment').text();
          $('#comment').val(commentBody);
          $('#edit-comment').modal();
        });

        $('#modal-save').click(function(){
            $.ajax({
                method: 'POST',
                url: urlEdit,
                data: {
                    comment: $('#comment').val(),
                    commentId: commentId,
                    _token: token,
                    _method: 'POST'
                 }
            })
            .done(function (msg){
                $(divcomment).text(msg['new_comment']);
                $('#edit-comment').modal('hide');
            });
        });

</script>

这是 HTML:

<article class="row">
    <div class="col-md-3 col-sm-3 hidden-xs">
        <figure class="thumbnail">
            <img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic  }}" />
            <figcaption class="text-center">{{ $comment->user->name }}</figcaption>
        </figure>
    </div>
    <div class="col-md-8 col-sm-8">
        <div class="panel panel-default arrow left">
            <div class="panel-body">
                <header class="text-left">
                    <div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}</div>
                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}</time>
                </header>
                <div id="comment-post" data-commentid="{{ $comment->id }}">
                    <p id="display-comment">{{ $comment->comment }}</p>
                </div>
            </div>

            <div class="panel-footer list-inline comment-footer">
                @if(Auth::guest())

                    No puedes responder ningún comentario si no has ingresado.

                @else

                    @if(Auth::user() == $comment->user)
                        <a href="#" data-toggle="modal" data-target="edit-comment" class="edit-comment">Editar</a> <a href="#" data-toggle="modal" data-target="delete-comment" class="delete-comment">Eliminar</a>
                    @endif

                    @if(Auth::user() != $comment->user)
                        <a href="#">Responder</a>
                    @endif

                @endif
            </div>

        </div>
    </div>
</article>

我的编辑模式:

<div class="modal fade" id="edit-comment" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" style="color:#000;">Editar Comentario</h4>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="comment">Editar comentario</label>
            <textarea class="form-control" name="comment" id="comment"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cerrar</button>
        <button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"><span class="glyphicon glyphicon-ok"></span> Editar</button>
      </div>
    </div>
  </div>
</div>

我的cmets更新路线:

Route::POST('comments/', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);

我在 CommentsController 上的更新功能:

public function update(Request $request)
{

    $this->validate($request, [
        'comment' => 'required'
    ]);

    $comment = Comment::find($request['commentId']);
    if (Auth::user() != $comment->user) {
        return redirect()->back();
    }

    $comment->comment = $request['comment'];

    $comment->update();
    return response()->json(['new_comment' => $comment->comment], 200);

}

最后是在我的 Post 单一视图“我显示 cmets 的位置”上创建的变量

<script>

  var token = '{{ Session::token() }}';
  var urlEdit = '{{ url('comments/update') }}';

</script>

更新:

评论表方案:

    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->text('comment');            
            $table->boolean('approved');
            $table->integer('post_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('comments', function ($table){
            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
        });
    }

新更新:

错误消息:

错误 1/3

SQLSTATE[23000]:违反完整性约束:1048 列“post_id”不能为空

错误 2/3

SQLSTATE[23000]:违反完整性约束:1048 列“post_id”不能为空

错误 3/3

SQLSTATE[23000]:完整性约束违规:1048 列“post_id”不能为空(SQL:插入commentscommentapprovedpost_iduser_idupdated_at,@ 987654334@) 值(另一条评论,1, , 4, 2017-06-04 04:54:34, 2017-06-04 04:54:34))

附加信息:

常规

Request URL:http://devmedia.dev/comments/update
Request Method:POST
Status Code:500 Internal Server Error
Remote Address:127.0.0.1:80
Referrer Policy:no-referrer-when-downgrade

表格

comment:Another yet comment
commentId:13
_token:Do1gqYfziHij1nAj2CFOWwgdt7UWuubqbawrD5uX
_method:POST

整个 cmets 路线:

Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);
Route::get('comments/{id}/edit', ['uses' => 'CommentsController@edit', 'as' => 'comments.edit']);
Route::POST('comments/', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);
Route::delete('comments/{id}', ['uses' => 'CommentsController@destroy', 'as' => 'comments.destroy']);
Route::get('comments/{id}/delete', ['uses' => 'CommentsController@delete', 'as' => 'comments.delete']);

【问题讨论】:

  • 尝试使用save()而不是update()来更新模型。
  • 请附上 cmets 表的架构。
  • 你好@Anton 看看上面有问题的更新
  • @JuanRincón 我注意到你的路由地址只是comments/,而你正在请求comments/update。这是一个错字,还是可能执行了错误的代码?
  • 我建议save() 而不是update() 因为update() 通常带一个参数;要设置为值的字段数组。我还没有看到它以其他方式使用,但我可能是错的。

标签: javascript php ajax laravel


【解决方案1】:

看来我(和Anton's)的预感是正确的。您有两条相互冲突的路线。

Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);

当然

Route::post('comments/', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);

因为这两条路由使用的路由大致相同,所以 laravel 只会走最先定义的那个,也就是你的comments.store 路由。

有几种方法可以解决这个问题。

  1. 更改路线的顺序:

    Route::post('comments/update', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);
    Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);
    Route::get('comments/{id}/edit', ['uses' => 'CommentsController@edit', 'as' => 'comments.edit']);
    
  2. 使用路由约束:

    Route::post('comments/{post_id}', [
        'uses' => 'CommentsController@store',
         'as' => 'comments.store'
    ])->where(['post_id' => '[0-9]+']);;
    Route::get('comments/{id}/edit', ['uses' => 'CommentsController@edit', 'as' => 'comments.edit']);
    Route::post('comments/update', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);
    

值得注意的是,我不知道 Facade 注册器如何处理 Facade 方法的大小写(lower, upper)。所以为了不引起更多错误,我使用了POST 的小写,就像它在文档中使用。

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 2020-02-12
    • 1970-01-01
    • 2018-04-16
    • 2016-03-24
    • 1970-01-01
    • 2017-03-07
    • 2017-04-12
    • 2019-12-05
    相关资源
    最近更新 更多