Kenziiee Flavius Kenziiee Flavius - 2 months ago 18
PHP Question

Undefined Offset 0: Laravel

I HAVE already read through the other similar questions on stackoverflow and none of them have helped me to find a solution.

This has be completely confused, what was once working has randomly broken and I have no idea whats wrong, the error doesn't seem logical to me i'll show you what i mean.

public function nGetOverviewAccounts()
{
$results = Account::where('archive', '=', false)->select('id', 'display_name', 'server_ip_address', 'server_password', 'status_type_id', 'account_type_id')->get()->toArray();

$index = 0;
$accounts = [];

foreach($results as $result)
{
$accountType = AccountType::where('id', $result['account_type_id'])->select('name')->get()->toArray();
$statusType = StatusType::where('id', $result['status_type_id'])->select('name')->get()->toArray();

return $accountType[0]['name']; //this works

$accounts[$index]['account_type'] = $accountType[0]['name']; //this doesnt..

$accounts[$index]['status_type'] = $statusType[0]['name'];

$index++;
}

return $accounts;
}


That code is right next to each other in the function. The array
$accountType
looks like this.

0:{name: "Google"}


Which shows that it has an index of 0 but its not working.

EDIT: PLEASE READ

Im going to clear something up i seems to have put it across wrongly to you guys, the return statement is added by me AFTER i get the undefined index error i only added it to the code to show that it works when i return it but when i try to assign its value to another variable (without the return statement) i get the undefined index error.

Answer

Try this:

public function nGetOverviewAccounts()
{
$results = Account::where('archive', '=', false)->select('id', 'display_name', 'server_ip_address', 'server_password', 'status_type_id', 'account_type_id')->get()->toArray();

$accounts = [];

foreach($results as $key => $result)
{
    $accountType  = AccountType::where('id', $result['account_type_id'])->select('name')->get()->toArray();
    $statusType   = StatusType::where('id', $result['status_type_id'])->select('name')->get()->toArray();

    if(!empty( $accountType[0]['name'])) && !empty( $statusType[0]['name'])){
    $accounts[$key]['account_type'] = $accountType[0]['name']; //this doesnt..

    $accounts[$key]['status_type']  = $statusType[0]['name']; 
  }
}

return $accounts;
}

Also if you want the first key of $accountType and $statusType then you can use first() instead of get(). If your keys are different then you can use the $index