Php 如何在控制器laravel中使用get对象

Php 如何在控制器laravel中使用get对象,php,laravel,model-view-controller,controller,laravel-5.2,Php,Laravel,Model View Controller,Controller,Laravel 5.2,我在控制器中有一个删除类别及其图像文件的函数。但我无法访问path属性。我收到此错误,未定义属性:Illumb\Database\Eloquent\Collection::$path。它正在返回路径,但我无法使用它 public function remove($id) { //$category = Category::find($id)->delete(); $category_image = CategoryImage::where('category_id', '

我在控制器中有一个删除类别及其图像文件的函数。但我无法访问path属性。我收到此错误,未定义属性:Illumb\Database\Eloquent\Collection::$path。它正在返回路径,但我无法使用它

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

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

    echo $category_image->path;


    //return back();
}

如果你得到一个集合,你必须以这种方式循环通过集合:

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

如果只需要获取一个对象,可以使用:

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

if (!is_null($category_image)) { // Always check if object exists.
    echo $category_image->path;
}
当您使用
get()
时,您将获得一个。在这种情况下,您可以迭代集合并从每个对象获取数据,或者只使用索引:

$category_image[0]->path;

如果不想像if($category_image){echo$category_image->path;}那样冗长,也可以使用if语句执行此操作