Brian Logan Brian Logan - 3 months ago 10
PHP Question

Laravel ->get() returning null

I have a collection in Laravel 5.3 that I created after a query, this

dd()
is just one item, didn't want to spam to much...

Collection {#950
#items: array:1 [
0 => Callrail {#942
#table: "callrails"
#appends: []
#with: []
#hidden: []
#casts: []
#connection: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:2 [
"hourofday" => 1
"calls" => 2
]
#original: array:2 [
"hourofday" => 1
"calls" => 2
]
#relations: []
#visible: []
#fillable: []
#guarded: []
#dates: []
#dateFormat: null
#touches: []
#observables: []
+exists: true
+wasRecentlyCreated: false
#forceDeleting: false
-originalData: []
-updatedData: []
-updating: false
-dontKeep: []
-doKeep: []
#dirtyData: []
}
]
}


EDIT #1:

Here is the
$calls->toJSON()
output:

[
{
"hourofday":1,
"calls":2
},
{
"hourofday":15,
"calls":1
},
{
"hourofday":16,
"calls":4
},
{
"hourofday":18,
"calls":7
},
{
"hourofday":19,
"calls":2
},
{
"hourofday":20,
"calls":1
},
{
"hourofday":22,
"calls":2
}
]


The problem is, when I try to do:

$i = 0;
while($i != 24) {
$response[] = array(
'name' => date('g A', strtotime('2016-01-01 '.$i.':00:00')),
'y' => $calls->whereStrict('hourofday', $i)->get('calls', 0);
);
$i++;
}


Every value in the
$response
always has
0
, or
null
if I don't put a default value in. The values exist, they are in the collection, and are properly formatted, but for whatever reason I can't get them. Is there something I am missing?

Current Documentation:

https://www.laravel.com/docs/5.3/collections#method-get

EDIT #2:

Found the answer with help from @Andrej Ludinovskov and the correct answer:

$i = 0;
while($i != 24) {
// You have to get the first item in the array, then you can use it like normal
$callCount = $calls->whereStrict('hourofday', $i)->first();
$response[] = array(
'name' => date('g A', strtotime('2016-01-01 '.$i.':00:00')),
'y' => ($callCount?$callCount->calls:0)
);
$i++;
}

Answer

You have collection of elements and it has keys start from 0 to n. The key 'calls' is a key of an item of this collection. So your code should look like:

$i = 0;
while($i != 24) {
    $item = $calls->whereStrict('hourofday', $i)->get(0, null);
    $cnt = 0;
    if ($item != null) {
        $cnt = $item->calls
    }
    $response[]  = array(
            'name' => date('g A', strtotime('2016-01-01 '.$i.':00:00')), 
            'y' => $cnt
        );
    $i++;

}