after filtering a plucked laravel collection, the indexed array change to Associative array - laravel

I have a collection of model eloquent such as user model, i use the pluck method to get the only post_idfrom this collection, this method give me the indexed array of post_id, but when i use filter or unique method for this indexed array the result change to Associative array. i don't want a assoc array in result. I want just the unique of post_id's in the indexed array. laravel auto changing my result.
$this->posts->pluck('post_id')->unique('post_id')
result is :{ "1": 1 , "2": 2 }.
Is this can a bug or I have a mistake in fetching data by methods?

You can use groupBy like this :
$this->posts->groupBy('post_id')->pluck('post_id');

Related

Laravel 9, split collection by column value

I have a table with types, and second table "cleanings" with a related type_id column.
I get a collection of all cleanings:
$cleanings= Cleaning::with(['propierty'])->get();
And now, I need to split this collection in many collections(or arrays), one for every type_id.
Is there any trick to do it? I can't find any method in collections page for that.
$array = [];
foreach($cleanings as $cleaning) {
$array[$cleaning->type_id][] = $cleaning;
}
This'll give you an array of arrays, keyed by type_id.

DB::get is Array in Laravel but it says it is not array

I thought the data which is from DB::get() is Array.
However , the console says it is not array.
$fruitList = Food::where('id' => 300)->get(['id']);
shuffle($fruitList);
ErrorException: shuffle() expects parameter 1 to be array, object given in file
The return value of get() is not an array. it's Laravel array collection you can convert it to an array or use shuffle of array collection:
$fruitList = Food::where('id' => 300)->get(['id'])->toArray();
shuffle($fruitList);
with array collection:
$fruitList = Food::where('id' => 300)->get(['id'])->shuffle();
Just like #A.seddighi mentioned, using get() or all() gives you a collection. It may seem like an array when you output it using return or print but it is different.
Collections can be filtered, queried and so on. e.g
$fruitList->has('price')
etc.
To get an array simply called the toArray() method on it, you may also use flatMap(), mapWithKeys() etc. Make sure you follow the documentation that is suitable for your version of laravel.

Laravel - How to extract one field for items in a model to an array?

I have a table that has a one-to-many relationship with another table.
Call them tables parent and child
child has a field called field1
I am trying to get an array of all field1 values.
In the parent Model, I have this function that gets me all children of parent
public function children()
{
return $this->hasMany(Child::class);
}
Now, in the parent model, I also want to get all field1 values.
I can get all the children like so:
$children = $this->children->all();
But I just can't figure out how to then index into this to get all the field1 values.
Maybe it is better to just use $this->children in which case it is a Collection and then use some sort of Collection method to extract field1?
I tried
$this->children->only(['field1'])
but that returned nothing, even though field1 certain exists.
Ideas?
Thanks!
You can use pluck method of collecion to get an array of field1 values:
$parent->child->pluck('field1');
Or better, you can use pluck method of query builder (see section Retrieving A List Of Column Values), being even more efficient, with same result:
$parent->child()->pluck('field1');
map() is the function you are looking.
$children = $this->children->all()->map(function($children) {
return $children->field1;
});
A shorter version using Higher Order Message.
$children = $this->children->all()->map->field1;

Extract only raw ids from an Eloquent collection

I need to get an array of integers, which will contain raw ids of Eloquent records. The following query
Quote::select('id')->get();
gets an eloquent collection instead of an array of integers. How to modify it, so it meets my requirements?
Try this code:
Quote::get(['id'])->toArray();
Or:
Quote::all(['id'])->toArray();
Or:
DB::table('quote')->select('id')->get()->toArray();
Or:
Quote::pluck('id')->toArray();

How to convert an eloquent query into an array

I have the following eloquent query which uses a many-to-many relationship to grab all groups associated with the authenticated user.
$usergr = Auth::User()->usergroup()->get();
Pivot table
ID|user_id|group_id
1 |1 |2
2 |1 |3
I would like to convert this to an array of group_id. So fare it is a collection object however I need this converted to an array to be used on another query.
I have this so far:
foreach ($usergr as $obj)
{
$array[]= (array) $obj;
}
The query I for teh array is below:
$usergrsub = DB::table('group_subjectlist')->whereIn('group_id', $array)
->select('subjectlist_id')
->distinct()->get();
However the query above is not recognising the $array variable
(I use version 4.2)
In this particular case, the lists() function may do what you want.
Auth::User()->usergroup()->lists('group_id')
Most result objects returned by Laravel's builders have a toArray() method that will convert the object into an array.
The whereIn method expects an array of values, but the result of get() will be a collection of objects, which if converted to an array will be an array of associative arrays.
If you need the get() result only for the whereIn query you should use lists('group_id') instead of get(). Otherwise consider using pluck('group_id').

Resources