如何在Laravel集合中编辑项目 [英] How to edit items in laravel collection
问题描述
我是laravel的新手,我运行查询并从数据库中获取行,我想在查看这些行之前对其进行编辑. 所以这是我的代码片段:
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);
}
输出截图:
我需要将所有'x'字符替换为numbertemplate
列的'-'.
I need to replace all the 'x' characters with '-' of numbertemplate
column..
推荐答案
如果要始终对模型进行此转换,则只需将以下访问器方法添加到模型类中即可:
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']);
}
现在,每次访问 $ customerCallPlan-> 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;
});
这篇关于如何在Laravel集合中编辑项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!