Laravel - Undefined property in a controller
Question
I"m trying to get lines from a Threads tables with comments. I do :
$posts = threads::where('published', '=', true)->orderBy('published_at', 'desc')->orderBy('created_at', 'desc')->orderBy('id', 'desc')->paginate(5);
$datas = [
'posts' => $posts,
'comments' => $posts->comments,
'count_comments' => count($posts->comments)
];
Laravel returns :
Undefined property: Illuminate\Pagination\Paginator::$comments
Solution
You can do this:
$posts = threads::with('comments')->where('published', '=', true)->orderBy('published_at', 'desc')->orderBy('created_at', 'desc')->orderBy('id', 'desc')->paginate(5);
$comments = [];
foreach ($post in $posts)
{
$comments[] = $post->comments;
}
$datas = [
'posts' => $posts,
'comments' => $comments,
'count_comments' => count($comments)
];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow