评论功能用laravel,哪里错了?

comment function with laravel, where is the mistake?

我正在使用 laravel 框架创建博客。我现在正在做一个评论功能,并完成了它的基本结构。好吧,在我看来有一个未定义变量($comments)的错误,所以我认为我的控制器或路由存在一些问题。也许你们中的某个人可以看一下?

我的评论功能路线:

Route::post('/comment', ['as' => 'postComment', 'uses' => 'Test\TestController@comment']);
Route::get('/comment/{id}', ['as' => 'getComment', 'uses' => 'Test\TestController@getcomment']);

带解说功能的控制器:

     public function comment(CommentRequest $request)
{
    Comment::create($request->all());
    return redirect()->back();
}

public function getcomment($id)
{
    $comments = Comment::where('thread_id', $id);
    return view('test.show', [
        'comments' => $comments
    ]);
}

以及我试图获取评论的视图:

@foreach($comments as $comment)
    {{ $comment }}
@endforeach

我在数据库中保存评论的评论功能可以正常工作。

感谢您的帮助!

您的代码仅创建 查询,实际上您并未执行 查询。您应该使用 get() 方法,如下所示:

Comment::where('thread_id', $id)->get();
// Result: array of Comment objects.

您的代码:

Comment::where('thread_id', $id);
// Result: Query builder object (Illuminate\Database\Eloquent\Builder).

为了说明,您可以像这样使用查询构建器对象:

// Create the query.
$query = Comment::where('thread_id', $id);
$query->where('content', 'LIKE', '%laravel%');

// Execute the query and return the actual comments.
$comments = $query->get();