D
D
Dmitry2018-08-07 19:37:10
Laravel
Dmitry, 2018-08-07 19:37:10

How to add element to Laravel collection?

There is a standard label with users users.
There is a selection:
$users = Users::all();
In the course of the code in the
foreach ($users as $user){
...
here you need to add a new field to $users
}
This is necessary so that later it is convenient to pull out new, additional data in the form.
Clearly here:
5b69ca7a9ec52273025529.png

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mShpakov, 2018-08-07
@liggth

$user->new_property = "some value";
$user-save();
Accordingly, the new property must be written in the fillable in the model and entered into the table. If I understand the question correctly

V
Vyacheslav Plisko, 2018-08-07
@AmdY

You need to add a get-set for the attribute and write it in $appends so that there are no problems with serialization https://laravel.com/docs/5.6/eloquent-serializatio...

G
Gennady, 2019-01-24
@GssGenic

foreach ($users as $user){
$user->setAttribute($key,$val)
}
This is if you don't need to touch tables. The lifetime is the current request. It can be convenient to stuff a collection with all the calculated elements and pass it as an interface to the template engine.
here are the methods of the Eloquent model.
https://laravel.com/api/5.7/Illuminate/Database/El...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question