Laravel 5 Querybuilder, simplified collection results

Asked

Viewed 97 times

2

I’m using the method get() of Laravel’s Querybuilder and would like to know if it is possible to return the id’s in a simple one-dimensional array, for example:

[35,45]

Instead of:

[{"id":35},{"id":45}]

2 answers

3


In that case you want a list of id’s.
It would look something like this:

$ids= DB::table('minha_tabela')->pluck('id');

You can see it on documentation here.

I hope I’ve helped.

1

Querybuilder is a framework that has an interface for constructing sql queries and its main feature is the abstraction of database platforms. I believe it doesn’t have collection handling tools, but you can solve your problem by making a Mapping in the collection.

Using the function array_map of PHP pass a Closure followed by the collection you want to map by implementing the return of the desired attribute.

Example:

$listaIds = array_map(function($obj){
                return $obj->id;
            }, $listaObjetos);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.