Laravel - get DB result without table column name
Asked Answered
A

4

7

I wanted to have the result with only the values not with the table column name in Laravel 4.2. For example,

$recs = DB::table('table_name')
        ->select('id', 'title')
        ->get();

the result is

array(2) {
  [0]=>
  object(stdClass)#863 (2) {
    ["id"]=>
    int(2)
    ["title"]=>
    string(8) "my title"
  }
  [1]=>
  object(stdClass)#862 (2) {
    ["id"]=>
    int(3)
    ["title"]=>
    string(10) "my title 2"
  }
}

but I want to have only the result NOT the column name, like

[
  2,
  "my title"
],
[
  3,
  "my title 2"
]

yes, I can make it by looping the result and make new array without column name. But is there are any way to get the result in this fashion using Laravel ?

Alysaalyse answered 23/3, 2017 at 13:54 Comment(0)
T
9

Try

$recs = DB::table('table_name')->pluck('id', 'title');
dd($recs->all());
Tombstone answered 23/3, 2017 at 13:58 Comment(2)
Oh sorry, you need to append all(). Check my code again.Tombstone
'pluck' returning a number and so it is showing error when put 'all()' to a numberAlysaalyse
B
1

You can use the map() and the array_values() methods:

$recs->map(function($i) {
    return array_values((array)$i);
})

I'm not sure about Laravel 4.2, but I've just tested it and it works perfectly in Laravel 5.3. If it doesn't work in 4.2, use the native array_map() function instead.

Benitabenites answered 23/3, 2017 at 14:5 Comment(2)
That is the only (nearly) correct answer for what I know. You'll just need to do return array_values($i->toArray()); to make use of array_values. That being said I'm really interested in use case for this (converting human-readable keys into indexes).Ea
@devk I've tested it too and since OP is using Query Builder here, toArray() will return an error. At least in 5.3 (not sure about 4.2 though). I've edited my code to cast objects to arrays. I've copied wrong code first. Thanks for mentioning that.Benitabenites
D
1

Reference

Try $recs->flatten()->all()

Update

Since your $recs looks like an array from your error. Try converting to collection. I hope this will work on v4.2

$recsCollection = new \Illuminate\Database\Eloquent\Collection($recs);
$recsCollection->flatten()->all();
Durance answered 23/3, 2017 at 14:6 Comment(4)
thanks for the reply... im getting error since im using Laravel 4.2 and the given reference is in 5.4Alysaalyse
getting error "Call to a member function flatten() on array"Alysaalyse
"Call to undefined function collect()" i think 'collect' is not supported at 4.2Alysaalyse
Updated the answer. collect helper function is not available in v4.2Durance
G
1

DB::table('table_name')->all()->lists('id', 'title')->toArray()

Referance: Retrieving A List Of Column Values

Guyguyana answered 12/9, 2018 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.