How to add new value in collection laravel

0 votes

I have the following loop where I try to add a new value:

 foreach ($pro->sig()->get() as $key => $sig) {
            $sig->val = 2;
        }

When I print the output of $pro->sig() I don't have the new value $sig->val

Dec 4, 2020 in Laravel by kartik
• 37,520 points
125 views

1 answer to this question.

0 votes

Hello @kartik,

If you have a collection you can use push or put method.

Example with put:

$collection = collect(['product_id' => 1, 'name' => 'Desk']);

$collection->put('test', 'test');

$collection->all();

The output will be:

['product_id' => 1, 'name' => 'Desk', 'test' => 'test']

Example with push:

$collection = collect([1, 2, 3, 4]);

$collection->push(5);

$collection->all();

Output:

[1, 2, 3, 4, 5]
answered Dec 4, 2020 by Niroj
• 82,760 points

Related Questions In Laravel

0 votes
1 answer

How to change value of a request parameter in laravel?

Hello @kartik, Use merge(): $request->merge([ 'user_id' => ...READ MORE

answered Aug 10, 2020 in Laravel by Niroj
• 82,760 points
2,632 views
0 votes
1 answer

How to validate an input field if value is not null in Laravel?

Hello @kartik, try using nullable as a rule 'password' ...READ MORE

answered Sep 25, 2020 in Laravel by Niroj
• 82,760 points
4,537 views
0 votes
1 answer

How can I create a migration to add a value to an enum in eloquent?

Hello @kartik, Try using this code: public function up() ...READ MORE

answered Nov 12, 2020 in Laravel by Niroj
• 82,760 points
872 views
0 votes
1 answer

How to make a new page with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18, 2020 in Laravel by Niroj
• 82,760 points
2,057 views
+1 vote
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18, 2020 in Laravel by Niroj
• 82,760 points
7,876 views
0 votes
1 answer

What is redirection in Laravel?

Named route is used to give specific ...READ MORE

answered Mar 18, 2020 in Laravel by Niroj
• 82,760 points
892 views
0 votes
1 answer

How to install Laravel via composer?

Hello, This is simple you just need to ...READ MORE

answered Mar 23, 2020 in Laravel by Niroj
• 82,760 points
712 views
+1 vote
1 answer

What are named routes in Laravel and How can specify route names for controller actions?

Hey @kartik, Named routing is another amazing feature of ...READ MORE

answered Mar 23, 2020 in Laravel by Niroj
• 82,760 points
8,364 views
+2 votes
2 answers

How to add a new column to existing table of laravel in a migration?

You need do little modification in your ...READ MORE

answered Dec 10, 2020 in Laravel by anonymous
• 82,760 points
34,448 views
0 votes
1 answer

How to manually create a new empty Eloquent Collection in Laravel?

Hello @kartik, It's not really Eloquent, to add ...READ MORE

answered Aug 11, 2020 in Laravel by Niroj
• 82,760 points
2,593 views