2016-12-16 29 views
2

我在控制器中有一個函數來刪除類別及其圖像文件。但我無法訪問路徑屬性。我得到這個錯誤未定義的屬性:Illuminate \ Database \ Eloquent \ Collection :: $ path。它正在返回路徑,但我無法使用它。如何在控制器中使用get對象laravel

public function remove($id) { 
    //$category = Category::find($id)->delete(); 

    $category_image = CategoryImage::where('category_id', '=', $id)->get(['path']); 

    echo $category_image->path; 


    //return back(); 
} 

回答

2

,如果你需要得到的只是一個對象時,您可以使用first()

$category_image = CategoryImage::where('category_id', '=', $id)->first(); 

if (!is_null($category_image)) { // Always check if object exists. 
    echo $category_image->path; 
} 

當您使用get()時,您會收到collection。在這種情況下,你可以遍歷集合,並從每個對象中獲取數據,或只使用索引:

$category_image[0]->path; 
+0

你也可以用if語句做,如果你不想那樣冗長 如果( $ category_image){ echo $ category_image-> path; } – Spholt

1

你得到一個集合,你必須循環通過量的集合是這樣的:

foreach ($category_image as $image) { 
echo $image->path; 

}

相關問題