0

Guys I'm trying to get the result form my database by laravel 5.5. If I run this code:

DB::table('comments')->get()

It will return an array which contains stdClasses. Now I want the key(index) of each stdClass in the array be ID of the stdClass.

I just want to know that laravel has this feature ?

Update: This is returned Array for example:

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 7
                    ....
                )
            [1] => stdClass Object
                (
                    [id] => 8
                    ....
                )
            [2] => stdClass Object
                (
                    [id] => 9
                    ....
                )

        )

)

notice above code. I want 7,8,9 to be instead of 0,1,2 .

Mahdi
  • 115
  • 2
  • 13

2 Answers2

2

Check this, https://laravel.com/docs/5.6/collections#method-pluck

DB::table('comments')->get()->pluck('id');

Edit It seems you want to key your array by id.

There is this method https://laravel.com/docs/5.6/collections#method-keyby , so it would be something with the looks of

DB::table('comments')->get()->keyBy('id')->all();
Sérgio Reis
  • 2,483
  • 2
  • 19
  • 32
0

you can use this code for 2 columns (for example 'title' and 'id'):

DB::table('comments')->get()->pluck('title', 'id');

tnx Sérgio Reis but you dont need ->all();

just:

DB::table('comments')->get()->keyBy('id');