Laravel 5 get attribute from collection - php

I have a $location collection that looks like this:
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 ▶}
]
}
So I am trying to get the formattedAddress like this:
$location[0]->formattedAddress
But I get the following error:
Cannot access private property
Geocoder\Provider\GoogleMaps\Model\GoogleAddress::$formattedAddress
Anyone can help me out here?

It's a collection Do it like this
$location->first()->formattedAddress

The variable is private, meaning you can only access it from within the same class. In this case, the class has a getter method called getFormattedAddress() you can use.
Source: https://github.com/geocoder-php/Geocoder/blob/master/src/Provider/GoogleMaps/Model/GoogleAddress.php#L182
Solution: $location->first()->getFormattedAddress()
And a bit of advice, if you don't understand the private part, you really should have a look at the PHP documentation on visibility: http://php.net/manual/en/language.oop5.visibility.php

First, try to get the first object with $model->first()
If not, try to use mutators:(Here an example)
public function getNameAttribute()
{
return $this->attributes['firstName'];
}

Related

How can access property of variable if difficult properties

How can I access property of this type of data: Below data are into $live variable.
$live = =array:17 [▼
"sensex" => {#1130 ▼
+"code": "200"
+"message": "Success"
+"data": {#1131 ▼
+"HIGH": "36551.86"
}
}
"nifty_50" => {#1132 ▶}
"nasdaq" => {#1134 ▶}
I am trying to access value of 'HIGH' property for $live variable in php. I have tried with below code but its give me error:
$live->sensex->data;
Error:
Trying to get property 'sensex' of non-object
EDITED:
I'm trying to access this data structured data which is $live,
$data =
{#1139 ▼
+"chart": {#1138 ▼
+"result": array:1 [▼
0 => {#1135 ▼
+"meta": {#1129 ▶}
+"timestamp": array:195 [▶]
+"indicators": {#1137 ▼
+"quote": array:1 [▼
0 => {#1136 ▼
+"open": array:195 [▶]
+"close": array:195 [▶]
+"high": array:195 [▶]
+"volume": array:195 [▶]
+"low": array:195 [▶]
}
]
}
}
]
+"error": null
}
}
Now How can I access +"open": array:195 directly?
It kind of looks like an associative array, then you will get the get the value by:
$live["sensex"] // etc.
You need to use Array syntax
$live['sensex']->data;
Here $live is an array. Actually, it's an associative array. 'sensex' is a class.
The syntax for getting value from an associative array:
$var_name["key_name"];
For Std class, the syntax is:
$class_name->proparty_name
But we can get proparty value from Std class using associative array syntax. So.
$class_name["proparty_name"] is also Valid.
So for your case, you can use both:
$live["sensex"]->data->HIGH
$live["sensex"]["data"]->HIGH
$live["sensex"]["data"]["HIGH"]
to access an index of an array you need to use ['particular_index_name'].
to access a property of an object you need to use ->particular_property_name.
in your case, $live is an array, sensex is an object and data is also an object.
so. to access the value of HIGH
$live['sensex']->data->HIGH;

Access element of JSON Object which is in an Array

How can you access a JSON object element that is in an array?
Ideally I would like to know how to do this if the array is of unknown size and also an unknown amount of JSON objects.
In the example below I would like to access id in JSON object 0 and 19.
array:1 [▼
0 => {#411 ▼
+0: {#157 ▶}
+1: {#167 ▶}
+2: {#192 ▶}
+3: {#200 ▶}
+4: {#206 ▶}
+5: {#227 ▶}
+6: {#235 ▶}
+7: {#259 ▶}
+8: {#269 ▶}
+9: {#281 ▶}
+10: {#299 ▶}
+11: {#308 ▶}
+12: {#316 ▶}
+13: {#325 ▶}
+14: {#335 ▶}
+15: {#352 ▶}
+16: {#362 ▶}
+17: {#380 ▶}
+18: {#390 ▶}
+19: {#402 ▼
+"created_at": "Mon Jan 23"
+"id": 823548040000000000
+"id_str": "823548040000000000"
+"text": "blah blah blah blah blah blah blah"
+"truncated": true
+"entities": {#403 ▶}
+"source": "Twitter Web Client"
+"in_reply_to_status_id": null
+"in_reply_to_status_id_str": null
+"in_reply_to_user_id": null
+"in_reply_to_user_id_str": null
+"in_reply_to_screen_name": null
+"user": {#406 ▶}
+"geo": null
+"coordinates": null
+"place": null
+"contributors": null
+"is_quote_status": false
+"retweet_count": 3
+"favorite_count": 8
+"favorited": false
+"retweeted": false
+"possibly_sensitive": false
+"lang": "en"
}
}
]
The top level is an array with one element indexed 0(first lines in your paste). I.e. $var[0].
$var[0] seems to contain an object if I interpret your paste correctly(the curly brace on "0 => {"). Therefor, if you want to access its parts you use ->, in your case $var[0]->0 or $var[0]->19.
Elements 0 and 19 are objects(curly braces). So to access them you do f.ex. $var[0]->0->created_at.
Edit: Accessing numerical object properties isn't as easy as one would wish. But if you cast the object as an array it can be done:
((array) $var[0])[0]->created_at
Explanation: $var[0] is an object, but its properties are numerical. This is where the T_LNUMBER error occurs. So we cast that object as an array: (array) $var[0]. To access element with index 0 in the resulting array it is wrapped in parentheses: ((array) $var[0])[0]. (Without the parentheses("(array) $var[0][0]") it would've been a 2-dimensional array). Now we are at the object with string keys, which can be accessed as usual.
SO question goes through this in more detail.
Do note that the code won't be reusable, it's tailor made for this particular case. So if this situation occurs iin other places you should probably write some function that converts your data from objects to arrays.
If you use json_decode() it will convert the JSON into a PHP variable. Then you can access the elements however you normally would (array indices, etc).
https://secure.php.net/manual/en/function.json-decode.php

Doctrine object incomplete when no session cookie, why?

I've encountered a silly problem this morning and I struggle to find a decent solution. Maybe you can tip me...
I've this simple function in a entity repository, with a simple query:
public function findAvailabilityByDr($delivery_round_id) {
$qb = $this->_em->createQueryBuilder()
->select('partial dro.{id},
partial drp.{id, maxDeliveries, countDeliveries},
partial zdd.{id, day},
partial rer.{id, maxOrders, countOrders}')
->from($this->_entityName, 'dro')
->leftJoin('dro.parts', 'drp')
->leftJoin('drp.day', 'zdd')
->leftJoin('drp.relayRounds', 'rer')
->where('dro.id = :delivery_round_id')
->setParameters(array(
'delivery_round_id' => $delivery_round_id,
));
dump($qb->getQuery()->getOneOrNullResult());
die();
}
At the first load (with no session cookie created), I got an incomplete result:
DeliveryRound {#342 ▼
-id: 117
-endOfOrdersDate: DateTime {#346 ▶}
-parts: PersistentCollection {#428 ▼
-snapshot: array:2 [ …2]
-owner: DeliveryRound {#342}
-association: array:15 [ …15]
-em: EntityManager {#695 …11}
-backRefFieldName: "deliveryRound"
-typeClass: ClassMetadata {#373 …}
-isDirty: false
#collection: ArrayCollection {#412 ▼
-elements: array:2 [▼
0 => DeliveryRoundPart {#425 ▼
-id: 134
-deliveryDate: DateTime {#347 ▶}
-deliveryHourStart: null
-deliveryHourEnd: null
-maxDeliveries: null <------ HERE !!!!!!!!!!!
-countDeliveries: null
-deliveryRound: DeliveryRound {#342}
-day: ZoneDeliveryDay {#1302 ▶}
-ordersCustomers: PersistentCollection {#358 ▶}
-ordersProviders: PersistentCollection {#410 ▶}
-relayRounds: PersistentCollection {#637 ▶}
-roadSheetOptimizationData: null
}
1 => DeliveryRoundPart {#1444 ▶}
]
}
#initialized: true
}
-ordersProvidersGenDate: null
-roadSheetPath: null
-roadSheetGenDate: null
-preparationSheetPath: null
-preparationSheetGenDate: null
-deliveryMailNotificationsSendingDate: null
-deliveryNotificationsSendingDate: null
#translations: PersistentCollection {#420 ▶}
#newTranslations: null
#currentLocale: "fr"
#defaultLocale: "fr"
}
And at the second call (refresh), the session cookie is created and the result is correct (maxDeliveries: 30 is a correct value):
DeliveryRound {#1657 ▼
-id: 117
-endOfOrdersDate: null
-parts: PersistentCollection {#1794 ▼
-snapshot: array:2 [ …2]
-owner: DeliveryRound {#1657}
-association: array:15 [ …15]
-em: EntityManager {#695 …11}
-backRefFieldName: "deliveryRound"
-typeClass: ClassMetadata {#1673 …}
-isDirty: false
#collection: ArrayCollection {#1795 ▼
-elements: array:2 [▼
0 => DeliveryRoundPart {#1747 ▼
-id: 134
-deliveryDate: null
-deliveryHourStart: null
-deliveryHourEnd: null
-maxDeliveries: 30 <------ HERE !!!!!!!!!!!
-countDeliveries: 0
-deliveryRound: DeliveryRound {#1657}
-day: ZoneDeliveryDay {#2063 ▶}
-ordersCustomers: PersistentCollection {#1904 ▶}
-ordersProviders: PersistentCollection {#1896 ▶}
-relayRounds: PersistentCollection {#2187 ▶}
-roadSheetOptimizationData: null
}
1 => DeliveryRoundPart {#2188 ▶}
]
}
#initialized: true
}
-ordersProvidersGenDate: null
-roadSheetPath: null
-roadSheetGenDate: null
-preparationSheetPath: null
-preparationSheetGenDate: null
-deliveryMailNotificationsSendingDate: null
-deliveryNotificationsSendingDate: null
#translations: PersistentCollection {#1799 ▶}
#newTranslations: null
#currentLocale: "fr"
#defaultLocale: "fr"
}
And when I use $qb->getQuery()->getArrayResult()
the results are correct in both cases.
WTF ? Is it bug ?
Thanks for your help !
EDIT
If I reduce it to its simplest expression, with no partial and a call from a controller, the bug is still there...
Repository:
public function findAvailabilityByDr($delivery_round_id) {
$qb = $this->_em->createQueryBuilder()
->select('dro,
drp')
->from($this->_entityName, 'dro')
->leftJoin('dro.parts', 'drp')
->where('dro.id = :delivery_round_id')
->setParameters(array(
'delivery_round_id' => $delivery_round_id,
));
return $qb->getQuery()->getOneOrNullResult();
}
Controller:
class StructureController extends BasePublicCommonController
{
public function indexAction()
{
$delivery_round = $this->getDoctrine()->getManager()->getRepository('ProxymartDeliveryBundle:DeliveryRound')->findAvailabilityByDr(117);
dump($delivery_round);
die();
}
}
This is for things like this I hate programming sometimes :)
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/partial-objects.html
I don't know about the cookie, but I know for arrayResult():
The partial object problem in general does not apply to methods or queries where you do not retrieve the query result as objects. Examples are: Query#getArrayResult() [...]

How to get a value from a Array symfony2.8

Hi everyone i'm looking for a way to get a value in a variable but i'm stuck with an array like
$prixArrayArticle = $article->getArticlePlateforme()->getValues();
dump($prixArrayArticle);
gives me
ReassortController.php on line 1149:
array:1 [▼
0 => ArticlePlateforme {#1469 ▼
-article: Article {#1321 ▶}
-plateforme: Plateforme {#1051 ▶}
-codeProduitGv: "365717 "
-fournisseurCommun: FournisseurAchatsAdherents {#1445 ▶}
-referenceFournisseur: "100050 "
-minimumCommande: 1
-colisage: 12
-qtePalette: 12
-decolisable: true
-stock: 182
-dateCreation: DateTime {#1326 ▶}
-present: true
-articleSubstitution: null
-prix: PersistentCollection {#1430 ▼
-snapshot: array:1 [ …1]
-owner: ArticlePlateforme {#1469}
-association: array:19 [ …19]
-em: EntityManager {#137 …11}
-backRefFieldName: null
-typeClass: ClassMetadata {#1261 …}
-isDirty: false
#collection: ArrayCollection {#1439 ▼
-elements: array:1 [▼
0 => Prix {#1412 ▼
-id: 4175988
-dateDebut: DateTime {#1325 ▶}
-dateFin: DateTime {#1324 ▶}
-prixNet: "4.970"
-prixVenteConseille: null
-quantiteMinimum: null
-type: "permanent"
-numeroPromo: null
-offreComplementaire: false
-minimumCommande: 0
-colisage: 0
-invisible: null
-present: true
}
]
}
#initialized: true
}
-prixPromo: PersistentCollection {#1399 ▶}
}
]
and this
$article = $requeteArticle->getQuery()->getSingleResult();
give me this
ReassortController.php on line 1129:
Article {#769 ▼
-id: 1000940
-nom: "FILM DE PAILLAGE FRAISES FRESAFILM 1M40X10M"
-nomCourt: "FILM PAILLAGE FRAISES 1M40X10M"
-gamme: 5
-ecoContribution: "0.00"
-ecoMobilier: "0.00"
-quantiteAchat: "1.00"
-nombreUvParUa: "1.00"
-prixVenteConseille: "9.50"
-present: true
-tauxTva: TauxTva {#908 ▶}
-marque: null
-articleGencod: PersistentCollection {#1007 ▶}
-sousFamille: SousFamille {#635 ▶}
-articlePlateforme: PersistentCollection {#960 ▶}
-uniteAchat: UniteConditionnement {#833 ▶}
-uniteVente: UniteConditionnement {#833 ▶}
}
how can i get the name value for example in a variable because the array only have one index and i really don't know how to get a value with this array
Assuming that the properties are protected and that you have getters for them in your ArticlePlateforme and Article class, you should be able to get them like that:
$articleName = $prixArrayArticle[0]->getArticle()->getNom();
Otherwise, if the properties are public, you could simply get them like:
$articleName = $prixArrayArticle[0]->article->nom;

Laravel 5 Query Builder not returning any data

I have some nested query in my application such as example follow.
$arrData = DB::table('service as tsv')
->select($afields)
->join('shops as ts', 'ts.id', '=', 'tsv.shop_id')
->where('ts.name','like','%'.$searchstring.'%');
if(!empty($type) && $type == 'individual')
$arrData->where('ts.type','=', '1');
$arrData->groupBy('tsv.id')->get();
This query not returning the exact output it display the content like
Builder {#351 ▼
#connection: MySqlConnection {#336 ▶}
#grammar: MySqlGrammar {#347 ▶}
#processor: MySqlProcessor {#348}
#bindings: array:5 [▶]
+aggregate: null
+columns: array:7 [▶]
+distinct: false
+from: "service as tsv"
+joins: array:3 [▶]
+wheres: array:3 [▶]
+groups: array:1 [▶]
+havings: null
+orders: array:1 [▶]
+limit: 4
+offset: 0
+unions: null
+unionLimit: null
+unionOffset: null
+unionOrders: null
+lock: null
#backups: []
#operators: array:26 [▶]
#useWritePdo: false
}
I want to display the data how should I access the data from this situation.

Categories