Reputation: 363
I'm trying to build a simple idea tracking/commenting system, and on the summary view page I want a little detail about each post. Currently the posts and replies both live in one posts
table, with a newtopic
boolean to designate top-level posts and a nullable replyto
to designate comments.
So I have my controller for the summary page like so:
public function index()
{
$ideas = DB::table('posts')->addSelect(DB::raw('*,posts.created_at as pca'))
->join('users', 'users.id', '=', 'posts.uid')
->where('newtopic','1')->orderBy('posts.id','desc')->get();
return view('ideas.home', ['ideas' => $ideas]);
}
That works well enough, but I'd also like to pull, at least, the comment count and vote count and pass that summary info on to the view. I can't see a good way to do it at the controller level as the @foreach
doesn't hit until it gets to the view. I'm still fairly new to laravel and the MVC pattern in general, is there a subcontroller/subview type thing I need to do to get the desired result?
home.blade.php:
@extends('master')
@section('content')
@foreach($ideas as $idea)
<div class="container">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">
<a href="{{ 'ideas/'.$idea->id }}">{{ $idea->subject }}</a>
</h3>
</div>
<div class="panel-body">
{{ $idea->content }}
</div>
<div class="panel-footer">
Posted by {{ $idea->username }} on {{ $idea->pca }}
</div>
</div>
</div>
@endforeach
@stop
Upvotes: 1
Views: 1500
Reputation: 4557
give this a shot maybe you will get the results you want.
$data = Idea::with('users','comments') -> where('newtopic',1) -> orderBy('id','DESC') -> get();
in your view you would iterate like you did,
@foreach($ideas as $idea)
$idea -> user -> username;
$idea -> comment -> count;
$idea -> content;
$idea -> ...
@endforeach
Upvotes: 2
Reputation: 2090
after ->get()
use ->toArray()
you will have the array to iterate over.
Upvotes: 1