多层评论系统 Laravel
我在使用刀片递归部分视图时遇到了困难。除了文件中的递归之外,大部分工作正常。comment.blade.php
我知道我需要用一个前厅来再次调用自己,但我不知道如何调用它。@include('articles.comments.comment', $comment)
article_comments表:
id
message
user_id
parent_id
created_at
updated_at
应用\文章.php类:
class Article extends Model {
protected $table = 'articles';
protected $fillable = [
'category',
'title',
'permalink',
'synopsis',
'body',
'source',
'show_author',
'published_at'
];
protected $dates = ['published_at'];
public function scopePublished($query)
{
$query->where('published_at', '<=', Carbon::now());
}
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::parse($date);
}
public function comments()
{
return $this->hasMany('App\Comments')->where('parent_id', 0);
}
}
应用\评论.php类:
class Comments extends Model {
protected $table = 'article_comments';
protected $fillable = [
'parent_id',
'message',
];
public function author() {
return $this->belongsTo('App\User');
}
public function children()
{
return $this->hasMany('App\Comments', 'parent_id');
}
public function countChildren($node = null)
{
$query = $this->children();
if (!empty($node)) {
$query = $query->where('node', $node);
}
$count = 0;
foreach ($query->get() as $child) {
// Plus 1 to count the direct child
$count += $child->countChildren() + 1;
}
return $count;
}
}
app\http\Controllers\ArticlesController.php:
public function show($permalink)
{
$article = Article::where('permalink', '=', $permalink)->with('comments','comments.author','comments.children')->first();
if ($article != null) {
$comments = $article->comments;
return view('articles.show', compact('article','comments'));
} else {
return redirect('/')->with('error', 'This article does not exist.');
}
}
resources\views\articles\show.blade.php
@if (count($comments) > 0)
<ul>
@foreach ($comments as $comment)
@include('articles.comments.comment', ['comment'=>$comment])
@endforeach
</ul>
@else
no comments
@endif
资源\视图\文章\注释\注释.blade.php
<li>
{{ $comment->message }}
@if (count($comment->children) > 0)
<ul>
@foreach ($comment->children as $child)
@include('articles.comments.comment', ['comment'=>$child])
@endforeach
</ul>
@endif
</li>
当前错误:
Invalid argument supplied for foreach() (View: /var/www/dev.example.com/resources/views/articles/comments/comment.blade.php) (View: