doujilou3903 2014-03-16 11:48
浏览 130
已采纳

Laravel在视图中获取Collection对象

in below code i have Eloquent command and that return Collection object and i can not fetch that into view.

$collection = DB::table('contents')
    ->join('categories', function($join)
    {
        $join->on('categories.id', '=', 'contents.category');
    })
    ->where('contents.id', '=', $id)
    ->get();

thats return single Collecton Object and i do not need to use foreach. how to fetch this collection object in view without usign foreach?

i get error after using this :

echo $collection->title;
{{ $collection->title }}

ERROR:

Trying to get property of non-object
  • 写回答

1条回答 默认 最新

  • duanche2007 2014-03-16 12:08
    关注

    What is a single collection object? You must be talking about a single model? Collections are always an array of models.

    Your query should be like:

    $collection = DB::table('contents')
                    ->join('categories', 'contents.category', '=', 'categories.id')
                    ->where('contents.id', '=', $id)
                    ->first();
    
    echo $collection->title;
    

    passing data to the view can be like:

    $data = array(
       'collection' => $collection
    );
    return View::make('collection', $data);
    

    accessing the data from the template:

    {{ $collection->title }}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部