2017-07-04 36 views
1

所以我的問題,打印結果在刀片的數據是從控制器,因此:非法串偏移和試圖獲得非對象的屬性(laravel 5.3)

  1. UseController.php:

     $expertCategory = Category::getCategoryByID($user_id); 
        $data = [ 'expertCategory' => $expertCategory ]; 
        return view('cms.user.edit', $data); 
    
  2. Category.php(型號)getCategoryByID($ USER_ID)返回結果數組,如果I DD(expertCategory);在控制器,其結果是:

    array:9 [▼ 
        "id" => 1 
        "name" => "Beauty" 
        "sequence" => 1 
        "background_color" => "ffffff" 
        "status" => "Active" 
        "created_at" => "2017-06-19 09:41:38" 
        "updated_at" => "2017-06-19 09:41:38" 
        "icon_filename" => "beauty-icon" 
        "iconURL" => array:3 [▼ 
          "small" => "http://localhost:8000/images/category_icons/small/beauty-icon" 
          "medium" => "http://localhost:8000/images/category_icons/medium/beauty-icon" 
        ] 
    ] 
    
  3. 但是,當我想用​​的foreach的結果blade.php與代碼打印:

    @foreach($expertCategory as $expertCat) 
        {{ $expertCat->id }} 
    @endforeach 
    

將返回錯誤「試圖讓非對象「

的屬性如果我使用這樣的代碼:

@foreach($expertCategory as $expertCat) {{ $expertCat['id'] }} @endforeach

則回覆:「非法串偏移‘身份證’」

有人能幫助解決這個問題:■?非常感謝 !

+0

不要做foreach,它只是'$ expertCategory [「id」]'。畢竟這是一個單一的類別。 – apokryfos

+0

[PHP:「注意:未定義的變量」,「注意:未定義的索引」和「注意:未定義的偏移量」的可能重複](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable- notice-undefined-index-and-notice-undef) –

+0

謝謝先生,這真的很有用,並且只是意識到我的查詢使用「first()」,這就是爲什麼每次使用時都會出錯。感謝你的幫助!上帝保佑! – Axel

回答

0

由於$expertCategory是一個dimensional array你正面臨這個問題

只需更換這

$expertCategory = Category::getCategoryByID($user_id); 
$data = [ 'expertCategory' => $expertCategory ]; 
return view('cms.user.edit', $data); 

隨着

$expertCategory = Category::getCategoryByID($user_id); 
$data = [ 'expertCategory' => [$expertCategory] ]; 
return view('cms.user.edit', $data); 

然後使用

@foreach($expertCategory as $expertCat) 
    {{ $expertCat['id'] }} 
@endforeach 

在你的刀片中它會爲你工作。

+0

謝謝先生Sahoo,只是意識到我的查詢選擇「first()」只有這就是爲什麼我不能用於每個。謝謝你的幫助先生! – Axel

+0

@Axel歡迎您,如果您的問題解決了,只需通過接受我的答案來關閉您的問題。謝謝:) –

+0

好吧,先生,完成,非常感謝:D – Axel

相關問題