How to edit items in laravel collection

By default php creates a copy of a variable when passing it to a function as a parameter. You can override this behaviour by prefixing the parameter with an ampersand, which will pass a pointer to the original variable to the function instead.

We can use this in a foreach loop inside the collection to modify the original item like so:

$callPlans->each(function(&$plan) {
    $plan->numbertemplate = 'xyz';
});

You could do the following:

$callPlans = CustomerCallPlan::whereNotNull('id')->get();

foreach ($callPlans as $callPlan) {
    $callPlan->numbertemplate = (whetever you need);
    $callPlan->save(); //save the changes
}

Hope this was helpful.


If you want to do this transformations always for your model, you can just add the following accessor method to the model class:

public function getNumbertemplateAttribute() {
  return str_replace('x', '-', $this->attributes['numbertemplate']);
}

Now everytime you access $customerCallPlan->numbertemplate you will get the converted string.

Otherwise just convert the column when you fetch the data:

$plans = $callPlans->get()->map(function($plan) {
  $plan->numbertemplate = str_replace('x', '-', $plan->numbertemplate);
  return $plan;
});