Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 530
Abrar Jahin Avatar asked Feb 08 '16 08:02

Abrar Jahin


People also ask

How do I change the date format in Laravel query?

You can always use Carbon's ->format('m/d/Y'); to change format. Or you can just use selectRaw to build your queries. Save this answer.

What does get () do in Laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.

What is withTrashed in Laravel?

Laravel, “withTrashed()” linking a deleted relationship With Eloquent we can define the relation easily. If the user gets deleted, and on the User model we use the SoftDeletes trait, you can use withTrashed() method here.

Is eloquent an ORM?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.


1 Answers

You can call pluck() 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

like image 138
Coloured Panda Avatar answered Sep 25 '22 23:09

Coloured Panda