Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit items in laravel collection

I am new in laravel, I run a query and get rows from database and I want to edit a column of this rows before get them in view. So here is my code piece :

$callPlans = CustomerCallPlan::whereNotNull('id');

foreach ($callPlans->get() as $callPlan) {
    dd($callPlan);
}

And the output screenshot:

enter image description here

I need to replace all the 'x' characters with '-' of numbertemplate column..

like image 344
TyForHelpDude Avatar asked Jun 02 '16 08:06

TyForHelpDude


4 Answers

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;
});
like image 185
jedrzej.kurylo Avatar answered Oct 23 '22 22:10

jedrzej.kurylo


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';
});
like image 36
Liquinaut Avatar answered Oct 23 '22 21:10

Liquinaut


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.

like image 4
Codearts Avatar answered Oct 23 '22 22:10

Codearts


You could use update() and str_replace() :

$callPlans = CustomerCallPlan::whereNotNull('id');

foreach ($callPlans->get() as $callPlan) {
    $callPlan->update(["numbertemplate"=>str_replace("x", "-", $callPlan->numbertemplate]);
}

Hope this helps.

like image 2
Zakaria Acharki Avatar answered Oct 23 '22 22:10

Zakaria Acharki