Abrar Jahin February 2016

Laravel 5.2 - Change Data Format get from Eloquent

I have a model like this-

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

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

[{"feature_id":2},{"feature_id":4},{"feature_id":9}]

But I want t output like this-

[2,4,9]

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.

Answers


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]

https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html#method_lists

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)
                   ->get();

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.

https://laravel.com/docs/5.2/collections#method-flatten

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

$flattened = $collection->flatten();

$flattened->all();

// ['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

Search




Leave an answer