Add simple array to Collection - php

in laravel this method is return Collection type of result:
$all_currency = CurrencyType::lists('currency_type', 'id');
Result:
Collection {#687 ▼
#items: array:2 [▼
1 => "EUR"
2 => "CHF"
]
}
now and i want to add -1 => "USD" to that. but i cant do it. my solution create nested array into that. for example:
$all_currency->push (["-1"=>"11"]);
Result:
Collection {#687 ▼
#items: array:4 [▼
1 => "EUR"
2 => "CHF"
3 => array:1 [▼
-1 => "USD"
]
]
}

If you need to use array, you can try to convert collection to an array with toArray() method:
$all_currency = CurrencyType::pluck('currency_type', 'id')->toArray();
$all_currency['-1'] = '11';
If you need to use collection, use put() helper:
$all_currency = CurrencyType::pluck('currency_type', 'id')->put('-1', '11');
Also, lists() is deprecated and will be removed in future, use pluck() instead.

Did you try to cast the collection to array before adding the currency?
Otherwise, it might help to check out the interface of the Collection class. Since you didn't mention it, it could be Doctrine or Propel or something else?
You then might find out, that there is a special function for adding a key-value pair, since pushing a value, adds that value (an array in your case) to the collection which is not what you want.
There might be no way of adding a value to a specific key index -1, that all depends on which ORM you are actually using and it's implementation.
//edit:
It seems the correct method is put and the code should look like this:
$all_currency->push (-1, "11");
https://laravel.com/api/master/Illuminate/Support/Collection.html#method_put

Use the put() method on your collection:
$all_currency->put(-1, "USD");
You can see all available methods for collections here: Collections

Related

How to convert Collection of array of arrays to Eloquent style Collection of Objects of Objects in Laravel

I'm pulling data from Airtable, which returns like so:
Illuminate\Support\Collection {#496 ▼
#items: array:11 [▼
0 => array:3 [▼
"id" => "rec4CaAx5EwGGi0I3"
"fields" => array:8 [▼
"description" => "Soft covers for switches"
"price" => 7
"tags" => array:2 [▼
0 => "recvPyxXM6GdIjgEr"
1 => "recvskfZPFMRPXzEb"
]
I can find how to convert to:
Collection of Objects of arrays, or even
Collection of Collections of Collections using recursive methods,
but not
Collection of Objects of Objects (of Objects)
so I can access the data like $data->fields->name like I can with normal Eloquent fetched results
Turns out I can use json encode / decode to convert it all to objects and then collect it#
$things = Airtable::table('things')->all();
$things = json_decode(json_encode($things),FALSE);
$things = collect($things);

get access to array build with pluck function in laravel

this is the query
$gg = DB::table('member_opinions')->where('user_id',$id)->pluck('committees_opinion');
result of dd($gg);
Illuminate\Support\Collection {#1436
#items: array:2 [
0 => "مؤهل"
1 => "غير مؤهل"
]
}
and I want to compare the values in loop in the controller
The each method iterates over the items in the collection and passes each item to a closure. Here you can compare the values.
$gg->each(function ($item, $key) {
//
});
More collections method is also present. Link for ref - https://laravel.com/docs/8.x/collections

Laravel /PHP Getting the keys from an array

I have a collection
Collection {#364 ▼
#items: array:2 [▼
24 => Collection {#375 ▼
#items: array:3 [▶]
}
0 => Collection {#376 ▶}
]
}
I try and convert to an array grab the keys and sort them
dd(sort(array_keys($group_ids->toarray())));
I get the error Only variables should be passed by reference
I need to convert this collection to an array of the keys in ascending order.
dd(array_keys($group_ids->toArray()));
seems to give what I need but I cannot convert it.
array:2 [▼
0 => 24
1 => 0
]
The Only variables should be passed by reference error is thrown because of the PHP's sort() function requires a reference and it can only be a variable not a return value from another function. To solve this error you can just use an intermediate variable like this:
$keys = array_keys($group_ids->toArray());
sort($keys);
Since you already using Laravel Collection, you can just use the keys() and the sort() methods instead. Suppose the $group_ids is an instance of Collection, you can extract the key and sort it ascendingly like this:
$sortedKeys = $group_ids->keys()->sort()->toArray();
Hope this help!
Below Solution is may be work for you.
When you call User::all() you get something like this:
0 => points: 10
1 => points: 50
2 => points: 30
3 => points: 70
4 => points: 20
What you can do is using the values() function, which will reset the keys of you collection:
0 => points: 70
1 => points: 50
2 => points: 30
3 => points: 20
4 => points: 10
May be you have try to sort data from the value. so key is automatically sorting out.
$users = User::all();
$users = $users->sortByDesc(function($item){
return $item->points()->sum('amount');
})->values();
I am not sure about this solution but hope it helps little bit with your question. in your question i didn't see any query so i have no much how you generate that collections.
Thanks

Laravel (5.3) pluck collection is returning other results than array

I've encoutered something strange. I'm making a selectbox, and i'm using the pluck method on a database model.
This piece of code:
$orgs = Organisation::pluck('name', 'id');
dd($orgs);
Gives me the following results:
Collection {#611 ▼
#items: array:6961 [▼
0 => "Test organisatie"
1 => "Name"
2 => "Another"
As you can see, the ID is not present.
Now when i make it into an array:
$orgs = Organisation::pluck('name', 'id')->toArray();
dd($orgs);
It gives the following results:
array:6961 [▼
1 => "Test organisatie"
3 => "Name"
19 => "Another"
The array is perfectly usable, i just don't understand why there's a difference.
--Edit:
When i use the collection in the select form helper, it does display the keys properly. Making me think it's a bug in the var dumper?
#Patrick Vd Pols
could you please try as below
Organisation::pluck('name','id')->all();

Manually add item to existing object [Laravel 5]

Here is what I try to do:
$q = Question::where('id',$id -> id)->get();
$q[] = $q->push([ 'test' => true]);
dd($q);
This will output:
Collection {#220 ▼
#items: array:3 [▼
0 => Question {#225 ▶}
1 => array:1 [▼
"test" => true
]
2 => null
]
}
So 'test' => true will append as a new key, but I want to insert it in Question so latter I can access to it like this with foreach $q -> test
So here is how I want access to item:
#foreach($q as $qq)
{{ $qq->test }}
#endforeach
It can be done by using setAttribute() function of Eloquent Model (https://github.com/illuminate/database/blob/master/Eloquent/Model.php).
As You can see it stores data in protected $attributes using setAttribute(), and when we do $SomeModel->some_field it uses magic method __get() to retrieve item by association from attributes array.
Here is the resolution to Your question:
$Question = Question::find($id);
$Question->setAttribute('test', 'blablabla');
Apart from setAttribute(), you can use put() refer to this post for one item. And map() for many items, refer to this post.

Categories