Search code examples
phplaraveleloquentlumen

Lumen/Laravel - Method to extract specific property from objects in an array of objects?


I have the following data:

    [{
      "id": 1,
      "name": "test1",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 2,
      "name": "test12",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 3,
      "name": "test123",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 4,
      "name": "test1234",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 5,
      "name": "test12345",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 6,
      "name": "test123456",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 7,
      "name": "test1234567",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 8,
      "name": "test12345678",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 9,
      "name": "test123456789",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 10,
      "name": "test1234567890",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 11,
      "name": "test12345678901",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 12,
      "name": "test123456789012",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }]

This data was retrieved via eloquent model, like this:

$ad_groups = Ad_user::find($request->decodedToken->user_id)->ad_groups()->get();

I don't know if any "inherited" functionality of eloquent model still resides within $ad_groups, thats why Im posting it here for you so you know what we have to work with ^^

What I basically want to accomplish is to get the ids extraced. I could of course just write a foreach loop. But I'm new to Lumen/Laravel and I'd like to know whether there is also some awesome method like ...>getMeWhatIWant() available in this context or not :D


Solution

  • You can use the pluck method on a Laravel collection (official docs here).

    You just have to pass the column name that you want to retrieve as first parameter:

    $ids = $ad_groups->pluck('id');
    dd($ids);