You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel动态评论模块开发遇500 Internal Server Error问题求助

Hey there! Let's troubleshoot that 500 Internal Server Error you're facing with your dynamic comment module. First, let's lay out your code clearly, then dive into the most likely causes and fixes.

Your Code Snippets

create.blade.php

<h1>Create comment</h1>
{!! Form::open(['id' => 'myForm', 'enctype' => 'multipart/form-data']) !!}
    <div class="form-group">
        {{ Form::textarea('body', '', ['class' => 'form-control', 'id' => 'article-ckeditor', 'placeholder' => 'Share your thoughts related to this post']) }}
    </div>
    {{ Form::hidden('post_id', $post->id) }}
    {{Form::submit('Submit', ['class' => 'btn btn-primary', 'id' => 'submitComment'])}}
{!! Form::close() !!}

AJAX Script

$(document).ready(function(){
    $('#submitComment').click(function(e){
        e.preventDefault();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url: "{{ url('/comments') }}",
            method: 'POST',
            data: {
                body: $('#article-ckeditor').val(),
                post_id: $('#post_id').val()
            },
            success: function(result){
                $('.alert').show();
                $('.alert').html(result.success);
            },
            error: function(jqXhr, json, errorThrown){
                var errors = jqXhr.responseJSON;
                var errorsHtml = '';
                $.each(errors['errors'], function (index, value) {
                    errorsHtml += '<ul class="list-group"><li class="list-group-item alert alert-danger">' + value + '</li></ul>';
                });
                swal({
                    title: "Error " + jqXhr.status + ': ' + errorThrown,
                    html: errorsHtml,
                    width: 'auto',
                    confirmButtonText: 'Try again',
                    cancelButtonText: 'Cancel',
                    confirmButtonClass: 'btn',
                    cancelButtonClass: 'cancel-class',
                    showCancelButton: true,
                    closeOnConfirm: true,
                    closeOnCancel: true,
                    type: 'error'
                }, function(isConfirm) {
                    if (isConfirm) {
                        $('#openModal').click();
                    }
                });
            }
        });
    });
});

Route

Route::resource('/comments', 'CommentsController');

CommentsController@store

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'body' => 'required'
    ]);

    if ($validator->fails()) {
        if($request->ajax()) {
            return response()->json(array(
                'success' => false,
                'message' => 'There are incorect values in the form!',
                'errors' => $validator->getMessageBag()->toArray()
            ), 422);
        }
        $this->throwValidationException(
            $request, $validator
        );
    }

    // Create Post
    $comment = new Comment;
    $comment->body = $request->body;
    $comment->user_name = auth()->user()->name;
    $comment->post_id = $request->post_id;
    $comment->profile_picture = auth()->user()->profile_picture;
    $comment->save();

    return response()->json(['success'=>'Data is successfully added']);
    //return redirect()->back()->with('success', 'Comment Created');
}

Most Likely Causes for the 500 Error

1. Unauthenticated User Trying to Comment

The biggest red flag here is that you're directly accessing auth()->user()->name and auth()->user()->profile_picture without checking if the user is logged in. If a guest submits a comment, auth()->user() returns null, and trying to access properties on null will throw a fatal error (which causes the 500).

Fix: Add an authentication check at the start of your store method:

public function store(Request $request)
{
    // Ensure user is logged in first
    if (!auth()->check()) {
        return response()->json([
            'success' => false,
            'message' => 'You need to log in to leave a comment.'
        ], 401);
    }

    // Rest of your validation and comment creation code...
}

2. Missing Fillable Fields in the Comment Model

Laravel blocks mass assignment by default. If your Comment model doesn't explicitly list the fields you're saving, the save() method might throw an error (sometimes resulting in a 500).

Fix: Update your Comment model to include these fields:

class Comment extends Model
{
    protected $fillable = ['body', 'user_name', 'post_id', 'profile_picture'];
    // ... rest of your model code
}

3. Unreliable Post ID Selection in AJAX

You're using $('#post_id').val() to get the post ID, but Form::hidden might not always set the id attribute (though it should here). To avoid potential conflicts, target the input by name instead:

Fix: Adjust the AJAX data section:

data: {
    body: $('#article-ckeditor').val(),
    post_id: $('input[name="post_id"]').val() // Use name attribute instead of id
},

4. Check Laravel Logs for Exact Error Details

500 errors are vague by nature—your best bet is to check the Laravel log file at storage/logs/laravel.log. Look for the most recent error entry right after you submit the comment; it will tell you exactly what's breaking (e.g., missing database column, undefined variable).

Quick Additional Checks

  • Make sure your comments database table has all the fields you're saving (body, user_name, post_id, profile_picture).
  • If profile_picture isn't a required field for users, set it to nullable in your database migration.

内容的提问来源于stack exchange,提问作者user9746625

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:15:00