Jonuux Jonuux - 5 months ago 48
PHP Question

Laravel get single column result as string

Hello I would like to know is it possible to get column value as string. Instead of array in array:

Current query:

Number::limit('1000')->get(['number'])->toArray()


The result at the moment is this:

Array in array

Preferable result:

String instead of array

Answer

Before your toArray() call, add pluck('number'):

$result = Number::limit('1000')->get(['number'])->pluck('number')->toArray();

That's it! This will pluck just the number attributes from your result collection, and give you a single-level array.


The reason this works, is because you are getting a Collection back from get():

All multi-result sets returned by Eloquent are an instance of the Illuminate\Database\Eloquent\Collection object, including results retrieved via the get method or accessed via a relationship.

And the pluck method:

https://laravel.com/docs/5.1/collections#method-pluck

Comments