[英]Laravel 5 accessing data with compact
大家好,
我希望我的帖子会有意义,并且您不会认为我是新手(有时我是..)
我试图了解什么是将数据发送到laravel 5中的视图并访问这些数据的最佳方法。
我实际上可以做到,但是在我看来这是错误的方法。
这是我的控制器:
public function timeline()
{
$array_articles = array();
$sharedcontents = DB::table('follow')->select(DB::raw('GROUP_CONCAT(sharedcontent_id) as concat_article_id'))
->join('sharedcontent_user', 'sharedcontent_user.user_id', '=', 'follow.user_id')
->where('follower_user_id', Auth::user()->id)
->groupBy('sharedcontent_user.sharedcontent_id')
->get();
foreach ($sharedcontents as $sharedcontent) {
$article_ids = $sharedcontent->concat_article_id;
$shareNumber = DB::table('sharedcontent_user')->where('sharedcontent_id', $article_ids)->count();
$row['share_number'] = $shareNumber;
$articles = DB::table('shared_content')
->select( 'sharedcontent_user.sharedcontent_id as sharedId',
'shared_content.id as articleId',
'shared_content.title as articleTitle',
'shared_content.source as articleSource',
'shared_content.image as articleImage'
)
->join('sharedcontent_user', 'sharedcontent_user.sharedcontent_id', '=', 'shared_content.id')
->join('users', 'users.id', '=', 'sharedcontent_user.user_id')
->get();
foreach ($articles as $article){
$shared_content_id = $article->articleId;
$row['title'] = $article->articleTitle;
$row['source'] = $article->articleSource;
$row['image'] = $article->articleImage;
}
array_push($array_articles, $row);
}
$articles = json_encode($array_articles);
return view('timeline', compact('articles'));
}
如您在开始时所看到的,我创建了一个名为$ array_articles的数组,然后将行插入其中。
在将其发送到视图之前,我先使用JSON对其进行编码,然后在视图中执行JSON解码。
我的观点:
<div id="timeline-container" class="container">
<?php $articles = json_decode($articles); ?>
@foreach ($articles as $article)
<div id="article-shared-box">
<div class="article-shared-box-left pull-left">
<div class="blend-layer">
<div class="article-shared-picture"><img src="{{ url($article->image) }}" /></div>
<div class="category-square">{{ $article->category }}</div>
<div class="article-shared-title">{{ $article->title }}</div>
<div class="article-shared-source">{{ $article->source }}</div>
</div>
...
如果我不执行此JSON编码和解码,则无法访问我的数据。
那我做对了吗?
@更新
如果我不使用JSON进行编码和解码,那么我总是得到:尝试访问非对象的属性,无论如何将其传递给视图,也不管如何调用数组。
这是我的$ article_array的print_r:
Array ( [0] => Array ( [share_number] => 1 [category] => Startup [sharing_user_id0] => 68 [sharing_user_name0] => 건우 박 [sharing_user_picture0] => https://graph.facebook.com/v2.4/723882664388388/picture?type=normal [comment_number] => 1 [most_recent_comment] => hhhh [comment_author] => 건우 박 [title] => 전북도 내 스타트업 육성 … 300억 규모 창조경제 혁신펀드 본격 운용 [source] => Platum [image] => http://platum.kr/wp-content/uploads/2015/07/11941_800799769932697_1056826482061661861_n.jpg ) [1] => Array ( [share_number] => 1 [category] => Startup [sharing_user_id0] => 68
您不需要编码和解码,因为这只会浪费时间。 您可以将PHP变量提供给您的视图,无需任何编码:
return view('timeline', array('articles' => (object) $array_articles));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.