Skip to content
Advertisement

PHP looping over data and getting key/value pairs

I’m using Laravel 8 to loop over some data. I’ve got my data out from my database, but am struggling to loop over the data in a foreach loop, it doesn’t appear to be giving me the key/value pairs, only the index/value pair?

$applicationOptions = ApplicationOptions::where('form_type', $form_type)->get();

foreach ($applicationOptions as $key => $value) {

  // only gives me: 0 - {"id": "3", "name": "john", "age": "20"} ...
  echo "${key} - ${value}";
}

But if I var_dump() my $applicationOptions I can see the array inside of the attributes and the original??

object(IlluminateDatabaseEloquentCollection)#279 (1) {
  ["items":protected]=>
  array(1) {
    [0]=>
    object(CompanyMyPackageApplicationOptions)#289 (27) {
      ["table":protected]=>
      string(38) "inbound_management_application_options"
      ["connection":protected]=>
      string(5) "mysql"
      ["primaryKey":protected]=>
      string(2) "id"
      ["keyType":protected]=>
      string(3) "int"
      ["incrementing"]=>
      bool(true)
      ["with":protected]=>
      array(0) {
      }
      ["withCount":protected]=>
      array(0) {
      }
      ["perPage":protected]=>
      int(15)
      ["exists"]=>
      bool(true)
      ["wasRecentlyCreated"]=>
      bool(false)
      ["attributes":protected]=>
      array(22) {
        ["id"]=>
        int(3)
        ["name"]=>
        string(6) "john"
        ["age"]=>
        int(20)
      }
      ["original":protected]=>
      array(22) {
        ["id"]=>
        int(3)
        ["name"]=>
        string(6) "john"
        ["age"]=>
        int(20)
      }
      ["changes":protected]=>
      array(0) {
      }
      ["casts":protected]=>
      array(0) {
      }
      ["classCastCache":protected]=>
      array(0) {
      }
      ["dates":protected]=>
      array(0) {
      }
      ["dateFormat":protected]=>
      NULL
      ["appends":protected]=>
      array(0) {
      }
      ["dispatchesEvents":protected]=>
      array(0) {
      }
      ["observables":protected]=>
      array(0) {
      }
      ["relations":protected]=>
      array(0) {
      }
      ["touches":protected]=>
      array(0) {
      }
      ["timestamps"]=>
      bool(true)
      ["hidden":protected]=>
      array(0) {
      }
      ["visible":protected]=>
      array(0) {
      }
      ["fillable":protected]=>
      array(0) {
      }
      ["guarded":protected]=>
      array(1) {
        [0]=>
        string(1) "*"
      }
    }
  }
}

How do I get access to that? It appears my query is returning the whole row key/value as a single object string too…

Advertisement

Answer

You get an collection of each item returned from the database. Each of these items is an instance of ApplicationOptions The key is the index in the collection. And has no relation to the database.

In laravel you have several methods you can call on a Collection. Your database would return an Instance of Illuminate/Database/Eloquent/Collection You can read up on collection methods here.

If you wish to retrieve a single attribute value, per item in your collection, you could use the pluck method on your result

$values = $applicationOptions->pluck('attributeName');

Alternatively you could loop through your collection using the each method

$applicationOptions->each(function (ApplicationOptions $applicationOption) {
    // insert any logic you want to do.
    echo $applicationOption->attributeName;
})

if you wish to use the result, map would be a better choice, you could also use mapWithKeys

$values = $applicationOptions->map(function (ApplicationOptions $applicationOption) {
    // You could also loop through the ApplicationOptions's attributes here using a foreach incase you wish to do something with it.
    return $applicationOption->attributeName;
})

$valuesWithKeys = $applicationOptions->mapWithKeys(function (ApplicationOptions $applicationOption) {
    return [$applicationOption->attributeNameYouWantToUseForKey => $applicationOption->attributeNameForValue];
})

if you just wish to key by a specific value, you could do that either in your sql query, or use the keyBy method on the collection

$values = $applicationOptions->keyBy('attributeName');

Finally, be aware that when you try to cast an Model instance to a string, laravel calls the toJson method on the model. hence why you get the json_encoded instance in your echo.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement