1myb
1myb

Reputation: 3596

Append a new property to an object

The following is the current array return from database via eloquent of laravel. I want to push something into the array and may i know how to?

The data in the return

Company Object ( 
[attributes] => Array ( 
    [id] => 1 
    [company_name] => superman 
    [company_fullname] => Superman Ent. ) 
[original] => Array ( 
    [id] => 1 
    [company_name] => superman 
    [company_fullname] => Superman Ent. ) 
[relationships] => Array ( ) 
[exists] => 1 
[includes] => Array ( ) ) 

while i can call this via foreach the array and access by {{ $x->company_name }}. I want to extend the array with some custom information like, total member count?

I tried in this way and failed.

$temp = array("count" => "1232");
array_push($companyInfo, $temp);

I got this

array_push() expects parameter 1 to be array, object given

Update The companyInfo array is return by laravel, and due to my foolish & careless (few days sleepless night +_+) i didn't notice everything is inside ['attributes']! The data can be access by the follow after applied methods from the answer.

{{ $x['attributes']['company_name'] }}
{{ $x[0]['count'] }}

Upvotes: 2

Views: 20321

Answers (3)

Amar Gharat
Amar Gharat

Reputation: 154

You have got array_push error because you passed an object instead of an array.

You're almost right just do following changes,

$companyInfo = (array)$companyInfo;

array_push($companyInfo, $temp);

Upvotes: 1

Maxim Kumpan
Maxim Kumpan

Reputation: 2635

$CompanyInfo in your case is an object. You need to either specify a named parameter to save your $temp array info:

$temp = array("count" => "1232");
$companyInfo->temp = $temp;

Or cast the object into an array:

$temp = array("count" => "1232");
$companyInfo = (array) $companyInfo;
array_push($companyInfo, $temp);

Upvotes: 3

RDK
RDK

Reputation: 4560

Try do it with out function array_push:

$temp = array("count" => "1232");
$temp[] = $companyInfo;

or

$temp = array("count" => "1232");
$temp['companyInfo'] = $companyInfo;
$temp['companyInfo']->getSomeData();

Upvotes: 2

Related Questions