Laravel 5从集合中获取属性

时间:2017-10-30 07:46:59

标签: php laravel laravel-5

我有一个$location集合,如下所示:

Collection {#225 ▼
  #items: array:5 [▼
    0 => GoogleAddress {#336 ▼
      -id: "ChIJjWwHAP72w0cR44_HJ-bRcJE"
      -locationType: "ROOFTOP"
      -resultType: array:1 [▶]
      -formattedAddress: ""
      -streetAddress: null
      -intersection: null
      -political: ""
      -colloquialArea: null
      -ward: null
      -neighborhood: null
      -premise: null
      -subpremise: null
      -naturalFeature: null
      -airport: null
      -park: null
      -pointOfInterest: null
      -establishment: null
      -subLocalityLevels: AdminLevelCollection {#339 ▶}
      -coordinates: Coordinates {#331 ▶}
      -bounds: Bounds {#332 ▶}
      -streetNumber: "21"
      -streetName: ""
      -subLocality: null
      -locality: ""
      -postalCode: ""
      -adminLevels: AdminLevelCollection {#337 ▶}
      -country: Country {#335 ▶}
      -timezone: null
      -providedBy: "google_maps"
    }
    1 => GoogleAddress {#344 ▶}
    2 => GoogleAddress {#352 ▶}
    3 => GoogleAddress {#360 ▶}
    4 => GoogleAddress {#368 ▶}
  ]
}

所以我试图像这样获取formattedAddress:

$location[0]->formattedAddress

但是我收到以下错误:

  

无法访问私有财产   地理编码器\提供商\ Google地图\模型\ GoogleAddress :: $ formattedAddress

任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:0)

变量是私有的,这意味着您只能从同一个类中访问它。在这种情况下,该类有一个可以使用的名为getFormattedAddress()的getter方法。

来源:https://github.com/geocoder-php/Geocoder/blob/master/src/Provider/GoogleMaps/Model/GoogleAddress.php#L182

解决方案:$location->first()->getFormattedAddress()

还有一些建议,如果你不了解私有部分,你真的应该看一下关于可见性的PHP文档:http://php.net/manual/en/language.oop5.visibility.php

答案 1 :(得分:0)

这是一个像这样的集合

$location->first()->formattedAddress

答案 2 :(得分:-1)

首先,尝试使用$ model-> first()获取第一个对象
如果没有,尝试使用mutators :(这里是一个例子)

public function getNameAttribute()
{
    return $this->attributes['firstName'];
}
相关问题