douleng3463 2015-08-20 03:33
浏览 135

如何在Laravel控制器中迭代foreach并将其传递给视图?

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
  • 写回答

2条回答 默认 最新

  • douyi4205 2015-08-20 03:36
    关注

    after ->get() use ->toArray() you will have the array to iterate over.

    评论

报告相同问题?

悬赏问题

  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo