Home Ask Login Register

Developers Planet

Your answer is one click away!

Abrar Jahin February 2016

Laravel 5.2 - Change Data Format get from Eloquent

I have a model like this-

$feature_project = FeatureProject::select(
                                            ->where('project_id', $project->id)

And if I return it, I am getting a output like this-


But I want t output like this-


So I need to convert the output.

But I am not finding a way without using for-each loop (make a temp array, push all elements to that array from current array with a for-each loop).

But I think there is more smart way than that in Laravel to do that.

I think Laravel Collection is used for this purpose.


Kaspars February 2016

You can call lists() method on the query builder.

$feature_project = FeatureProject::select('feature_id')
                                        ->where('project_id', $project->id)
                                        ->pluck('feature_id'); // [2,4,9]


Alternatively, you can use PHP's array_column() function for raw arrays. http://php.net/manual/en/function.array-column.php

Ali February 2016

An alternative way also will be helpful in some cases. We can run raw queries inside select function. Here is an example:

$feature_project = FeatureProject::select(DB::raw('GROUP_CONCAT("feature_id")))
                   ->where('project_id', $project->id)

In DB::raw we can run mysql query with function and case same as mysql query.

Tim Selaty Jr. February 2016

In Laravel's collections, you can call a method called Flatten, which flattens a multi-dimensional collection into a single dimension.


$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);

$flattened = $collection->flatten();


// ['taylor', 'php', 'javascript'];

With a fairly flat object, it should return just the values.

Ralph John Galindo February 2016

Use pluck():

$feature_project = FeatureProject::where('project_id', $project->id)->pluck('feature_id');

Zakaria Acharki February 2016

You can use lists() and toArray() :

$feature_project=FeatureProject::where('project_id', $project->id)->lists('id')->toArray();

Hope this helps.

Post Status

Asked in February 2016
Viewed 1,943 times
Voted 9
Answered 5 times


Leave an answer

Quote of the day: live life