我如何才能只显示在 Laravel 9 中验证的评论?

How can I only show comments that are verified in Laravel 9?

我有一个评论库应用程序,我希望用户能够在其中发表评论,但这些评论必须先由管理员验证才能显示。所以我希望用户只看到经过验证的评论,但我不知道如何在 Laravel.

中完成此操作

在我的数据库中,未验证的评论用 verified_status = 0 表示,已验证的评论是 verified_comments = 1。 所以我只希望用户看到 verified_status = 1

的评论

路线

// for users
Route::group(['middleware' => ['auth', 'role:user']], function() { 
    Route::get('/dashboard/myprofile', 'App\Http\Controllers\DashboardController@myprofile')->name('dashboard.myprofile');
    Route::get('/user-view', [CommentController::class, 'index'])->name('user-view');
    Route::post('save-comment-user', [CommentController::class, 'storeUser']);
    Route::get('fetch-comments-user', [CommentController::class, 'fetchCommentUser']);
    Route::get('edit-comment-user/{id}', [CommentController::class, 'editUser']);
    Route::put('update-comment-user/{id}', [CommentController::class, 'updateUser']);
});

评论控制器

public function fetchCommentUser()
{
    $comments = Comment::all();

    return response()->json([
        'comments'=>$comments,
    ]);
}

public function storeUser(Request $request)
{
    $validator = Validator::make($request->all(), [
        'comment_body'=>'required',
        'first_name'=>'required',
        'last_name'=>'required',
        'email'=>'required',
        'comment_tone'=>'required',
        'comment_type'=>'required',
        'verified_status'=>'required',
    ]);

    if($validator->fails())
    {
        return response()->json([
            'status'=>400,
            'errors'=>$validator->messages()
        ]);
    } else {
        $comment = new Comment;
        $comment->comment_body = $request->input('comment_body');
        $comment->first_name = $request->input('first_name');
        $comment->last_name = $request->input('last_name');
        $comment->email = $request->input('email');
        $comment->comment_tone = $request->input('comment_tone');
        $comment->comment_type = $request->input('comment_type');
        if ($request->has('verified_status')){
            $comment->verified_status = 0;
        } else{
            $comment->verified_status = 1;
        }
        $comment->save();

        return response()->json([
            'status'=>200,
            'message'=>'Comment Added Successfully.'
        ]);
    }
}
  
public function updateUser(Request $request, $id)
{
    $validator = Validator::make($request->all(), [
        'comment_body'=>'required',
        'first_name'=>'required',
        'last_name'=>'required',
        'email'=>'required',
        'comment_tone'=>'required',
        'comment_type'=>'required',
        'verified_status'=>'required',
    ]);

    if($validator->fails())
    {
        return response()->json([
            'status'=>400,
            'errors'=>$validator->messages()
        ]);
    } else {
        $comment = comment::find($id);
        if($comment)
        {
            $comment->comment_body = $request->input('comment_body');
            $comment->first_name = $request->input('first_name');
            $comment->last_name = $request->input('last_name');
            $comment->email = $request->input('email');
            $comment->comment_tone = $request->input('comment_tone');
            $comment->comment_type = $request->input('comment_type');
            $comment->verified_status = $request->input('verified_status');
            $comment->update();

            return response()->json([
                'status'=>200,
                'message'=>'Comment with id:'.$id. ' Updated Successfully.'
            ]);
        } else {
            return response()->json([
                'status'=>404,
                'message'=>'No Comment Found.'
            ]);
        }
    }
}

public function editUser($id)
{   
    $comment = Comment::find($id);
    if($comment)
    {
        return response()->json([
            'status'=>200,
            'comment'=> $comment,
        ]);
    } else {
        return response()->json([
            'status'=>404,
            'message'=>'No Comment Found.'
        ]);
    }
}

user-view.blade.php Blade 文件(用户看到的)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Comment Bank</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>

<x-app-layout>
    <div class="container mt-2">
        <x-slot name="header">
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                {{ __('Dashboard') }}
            </h2>
        </x-slot>
        <div class="row">
            <div class="col-md-12 card-header text-center font-weight-bold">
                <h2>Comment Bank</h2>
            </div>
            <div id="message"></div>
            <div class="col-md-12 mt-1 mb-2">
                <button type="button" id="addNewCommentUser" class="btn btn-success">Add</button>
            </div>
            <div class="col-md-12">
                <table id="Table1" class="table">
                    <thead>
                    <tr>
                        <th scope="col">Message Select</th>
                        <th scope="col">#</th>
                        <th scope="col">Comment Body</th>
                        <th scope="col">First Name</th>
                        <th scope="col">Last Name</th>
                        <th scope="col">Email</th>
                        <th scope="col">Comment Tone</th>
                        <th scope="col">Comment Type</th>
                        <th scope="col">Verified Status</th>
                    </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
                <input id="btnGet" type="button" value="Get Selected"/>
            </div>
        </div>
        <div><textarea id="messageList" rows="10" cols="100">Selection</textarea>
            <button type="button" id="copy">Copy</button>
        </div>
    </div>
    
    <!-- boostrap model -->
    <div class="modal fade" id="comments-crud-model" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="commentsCrudModel"></h4>
                </div>
                <div class="modal-body">
                    <ul id="msgList"></ul>
                    <form action="javascript:void(0)" id="addEditCommentFormUser" name="addEditCommentFormUser"
                          class="form-horizontal" method="POST">
                        <input type="hidden" name="id" id="id">
                        <div class="form-group">
                            <label for="name" class="col-sm-4 control-label">Comment Body</label>
                            <div class="col-sm-12">
                                <textarea class="form-control" id="comment_body" name="comment_body" rows="4" cols="10"
                                          placeholder="Enter Comment Body"></textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-4 control-label">First Name</label>
                            <div class="col-sm-12">
                                <input type="text" class="form-control" id="first_name" name="first_name"
                                       placeholder="Enter First Name" value="" required="">
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-4 control-label">Last Name</label>
                            <div class="col-sm-12">
                                <input type="text" class="form-control" id="last_name" name="last_name"
                                       placeholder="Enter Last Name" value="" required="">
                            </div>
                        </div>


                        <div class="form-group">
                            <label class="col-sm-4 control-label">Email</label>
                            <div class="col-sm-12">
                                <input type="text" class="form-control" id="email" name="email"
                                       placeholder="Enter Email" value="" required="">
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-4 control-label">Comment Tone</label>
                            <div class="col-sm-12">
                                <select name="comment_tone" id="comment_tone" class="form-control">
                                    <option value="1">Positive</option>
                                    <option value="0">Negative</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-4 control-label">Comment Type</label>
                            <div class="col-sm-12">
                                <select name="comment_type" id="comment_type">
                                    <option value="CO">Conclusion Comments</option>
                                    <option value="RO">Results Comments</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-primary" id="btn-add" value="addNewCommentUser">Save
                            </button>
                            <button type="submit" class="btn btn-primary" id="btn-save" value="UpdateCommentUser">Save
                                changes
                            </button>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                </div>
            </div>
        </div>
    </div>
</x-app-layout>


<!-- end bootstrap model -->
<script>
    $(document).ready(function ($) {
        fetchCommentUser(); // Get the table from the dB to start
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        function fetchCommentUser() {
            $.ajax({
                type: "GET",
                url: "fetch-comments-user",
                dataType: 'json',
                success: function (res) {
                    $('tbody').html("");
                    $.each(res.comments, function (key, item) {
                        $('tbody').append('<tr>\
<td><input type="checkbox" name="comments_to_copy" id="comments_to_copy' + item.id + '"/></td>\
<td>' + item.id + '</td>\
<td>' + item.comment_body + '</td>\
<td>' + item.first_name + '</td>\
<td>' + item.last_name + '</td>\
<td>' + item.email + '</td>\
<td>' + item.comment_tone + '</td>\
<td>' + item.comment_type + '</td>\
</tr>');
                    });
                },
                complete: function () {
                    isChecked();
                }
            });
        }

        $('#addNewCommentUser').click(function (evt) {
            evt.preventDefault();
            $('#addEditCommentFormUser').trigger("reset");
            $('#commentsCrudModel').html("Add Comment");
            $('#btn-add').show();
            $('#btn-save').hide();
            $('#comments-crud-model').modal('show');
        });
        
        $('body').on('click', '#btn-add', function (event) {
            event.preventDefault();
            var comment_body = $("#comment_body").val();
            var first_name = $("#first_name").val();
            var last_name = $("#last_name").val();
            var email = $("#email").val();
            var comment_tone = $("#comment_tone").val();
            var comment_type = $("#comment_type").val();
            var verified_status = 0
            $("#btn-add").html('Please Wait...');
            $("#btn-add").attr("disabled", true);

            $.ajax({
                type: "POST",
                url: "save-comment-user",
                data: {
                    comment_body: comment_body,
                    first_name: first_name,
                    last_name: last_name,
                    email: email,
                    comment_tone: comment_tone,
                    comment_type: comment_type,
                    verified_status: verified_status,
                },
                dataType: 'json',
                success: function (res) {
                    console.log(res);
                    if (res.status == 400) {
                        $('#msgList').html("");
                        $('#msgList').addClass('alert alert-danger');
                        $.each(res.errors, function (key, err_value) {
                            $('#msgList').append('<li>' + err_value + '</li>');
                        });
                        $('#btn-save').text('Save changes');
                    } else {
                        $('#message').html("");
                        $('#message').addClass('alert alert-success');
                        $('#message').text(res.message);
                        fetchCommentUser();
                    }
                },
                complete: function () {
                    $("#btn-add").html('Save');
                    $("#btn-add").attr("disabled", false);
                    $("#btn-add").hide();
                    $('#comments-crud-model').modal('hide');
                    $('#message').fadeOut(4000);
                }
            });
        });
        $('body').on('click', '.edit', function (evt) {
            evt.preventDefault();
            var id = $(this).data('id');

            $.ajax({
                type: "GET",
                url: "edit-comment-user/" + id,
                dataType: 'json',
                success: function (res) {
                    console.dir(res);
                    $('#commentsCrudModel').html("Edit Comment");
                    $('#btn-add').hide();
                    $('#btn-save').show();
                    $('#comments-crud-model').modal('show');
                    if (res.status == 404) {
                        $('#msgList').html("");
                        $('#msgList').addClass('alert alert-danger');
                        $('#msgList').text(res.message);
                    } else {
                        $('#comment_body').val(res.comment.comment_body);
                        $('#first_name').val(res.comment.first_name);
                        $('#last_name').val(res.comment.last_name);
                        $('#email').val(res.comment.email);
                        $('#comment_tone').val(res.comment.comment_tone);
                        $('#comment_type').val(res.comment.comment_type);
                        $('#verified_status').val(res.comment.verified_status);
                        $('#id').val(res.comment.id);
                    }
                }
            });
        });
        $('body').on('click', '.delete', function (evt) {
            evt.preventDefault();
            if (confirm("Delete Comment?") == true) {
                var id = $(this).data('id');
                $.ajax({
                    type: "DELETE",
                    url: "delete-comment-user/" + id,
                    dataType: 'json',
                    success: function (res) {
                        if (res.status == 404) {
                            $('#message').addClass('alert alert-danger');
                            $('#message').text(res.message);
                        } else {
                            $('#message').html("");
                            $('#message').addClass('alert alert-success');
                            $('#message').text(res.message);
                        }
                        fetchCommentUser();
                    }
                });
            }
        });
        $('body').on('click', '#btn-save', function (event) {
            event.preventDefault();
            var id = $("#id").val();
            var comment_body = $("#comment_body").val();
            var first_name = $("#first_name").val();
            var last_name = $("#last_name").val();
            var email = $("#email").val();
            var comment_tone = $("#comment_tone").val();
            var comment_type = $("#comment_type").val();
            var verified_status = $("#verified_status").val();
            $("#btn-save").html('Please Wait...');
            $("#btn-save").attr("disabled", true);
            $.ajax({
                type: "PUT",
                url: "update-comment-user/" + id,
                data: {
                    comment_body: comment_body,
                    first_name: first_name,
                    last_name: last_name,
                    email: email,
                    comment_tone: comment_tone,
                    comment_type: comment_type,
                    verified_status: verified_status,
                },
                dataType: 'json',
                success: function (res) {
                    console.log(res);
                    if (res.status == 400) {
                        $('#msgList').html("");
                        $('#msgList').addClass('alert alert-danger');
                        $.each(res.errors, function (key, err_value) {
                            $('#msgList').append('<li>' + err_value + '</li>');
                        });
                        $('#btn-save').text('Save changes');
                    } else {
                        $('#message').html("");
                        $('#message').addClass('alert alert-success');
                        $('#message').text(res.message);
                        fetchCommentUser();
                    }
                },
                complete: function () {
                    $("#btn-save").html('Save changes');
                    $("#btn-save").attr("disabled", false);
                    $('#comments-crud-model').modal('hide');
                    $('#message').fadeOut(4000);
                }
            });
        });
        $("#btnGet").click(function () {
            var message = "";
            
            // Loop through all checked CheckBoxes in GridView.
            $("#Table1 input[type=checkbox]:checked").each(function () {
                var row = $(this).closest("tr")[0];
                message += " " + row.cells[2].innerHTML;
                message += "\n-----------------------\n";
            });
            
            // Display selected Row data in Alert Box.
            $("#messageList").html(message);
            return false;
        });
        
        $("#copy").click(function () {
            $("#messageList").select();
            document.execCommand("copy");
            alert("Copied On clipboard");
        });
        
        function isChecked() {
            $("#Table1 input[type=checkbox]").each(function () {
                if ($(this).val() == 1) {
                    $(this).prop("checked", true);
                } else {
                    $(this).prop("checked", false);
                }
            });
        }
    });
</script>
</body>
</html>

fetchCommentUser 方法中尝试这个 where 条件:

public function fetchCommentUser()
{
    $comments = Comment::where('verified_status', 1)->get();

    return response()->json([
        'comments' => $comments,
    ]);
}

与该用户只会获得经过验证的评论。