Laravel 5.2 - Change the data format from Eloquent

I have such a model -

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

And if I return it, I get a conclusion like this -

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

But I want t to be output as follows:

 [2,4,9] 

So, I need to convert the output.

But I don’t find a way without using the for-each loop (I create a temp array, push all the elements into this array from the current array with the for-each loop).

But I think there is a smarter way to do this in Laravel.

I think the Laravel Collection is used for this purpose.

+6
source share
5 answers

You can call the pluck() method in 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 the PHP array_column() function for raw arrays. http://php.net/manual/en/function.array-column.php

+4
source

In Laravel collections, you can call the Flatten method, which aligns a multidimensional collection into one 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 only values.

+3
source

Use pluck() :

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

An alternative method will also be useful in some cases. We can run raw queries inside the 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 a mysql query with a function that is the same as a mysql query.

0
source

You can use lists() and toArray() :

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

Hope this helps.

0
source

All Articles