2016-06-14 66 views
1

我有一個控制器,在那裏我得到未登錄用戶項目的未讀評論。現在我的問題是我需要在我的導航部分中的這些數據顯示在我所有的意見。但不幸的是這不起作用。Laravel 5.1將數據傳遞給部分

這裏是我的路線:

Route::get('/', '[email protected]'); 

這裏是我的功能在我KlantController

public function getUnreads(){ 
     $uid = Auth::user()->id; 
     $projects = User::find($uid)->projects; 

     //comments 
     if (!empty($projects)) { 
      foreach ($projects as $project) {  
       $comments_collection[] = $project->comments; 
      } 
     } 

     if (!empty($comments_collection)) { 
      $comments = array_collapse($comments_collection); 
      $unreads = collect($comments)->where('unread', "1")->count(); 
     } 
     return view('partials.nav', $unreads); 
    } 

這裏的地方我在局部使用這些數據。

@if($unreads > 0) 
    <span class="label label-danger">{{ $unreads }}</span> 
@endif 

討厭這足以讓我多次以下錯誤:

Undefined variable: unreads (View: /var/www/resources/views/partials/nav.blade.php) 

任何人有任何想法,我怎麼能解決這個問題?任何幫助表示讚賞!

提前:)

回答

0

非常感謝試試這個:

在你的函數:

return view('partials.nav', ['unreads' => $unreads]); 

在你看來:

@if(count($unreads) > 0) 
    @foreach ($unreads as $unread) 
    <span class="label label-danger">{{ $unread }}</span> 
    @endforeach 
@endif 
+0

這不起作用不幸的是,我仍然得到相同的錯誤:( – Cruzito

+0

你會得到相同的錯誤?未定義變量'未讀'? –

+0

是的,我這樣做,我真的得到它3次,我認爲這是因爲我在我的數據庫中有3條評論 – Cruzito

1

你逝去的應該是數據一個包含鍵/值對的數組。

Laravel documentation

When passing information in this manner, $data should be an array with key/value pairs. Inside your view, you can then access each value using its corresponding key

在你的情況,你可以使用compact功能。

return view('partials.nav', compact('unreads')); 
+0

我仍然得到相同的錯誤:'( – Cruzito

+0

定義你的功能作爲'公共函數getUnreads($ unreads = 0)'。因爲如果沒有任何評論,unreads變量是未定義的。不幸的是, – Burak

+0

似乎也沒有工作 – Cruzito

0
return view('partials.nav')->with(['unreads' => $unreads]); 

而在你的控制器,你就可以開始這樣說:

$uid = Auth::user()->id; 
$projects = User::find($uid)->projects; 
$unreads = 0 

所以,如果世界上沒有其他意見,$ unreads瓦爾將在您的視圖是否存在呢。