Fan Fan - 5 months ago 80
PHP Question

How to change the value in laravel 5 collection

I have some problems here.
I get a collection which like:

$VenderData=Vender::where('active', '=', '1')->get();


Inside the collection i have a column called 'type' and the data looks like
'A1,A2,A3,'

or
'A1,A3,'

I want to transfer those codes to real names from
another table 'vender_type'.

code name
A1 XX
A2 OO
A3 ZZ


then add a new column into the original collection $VenderData.

How can i do this?

Answer

You must split the type attribute (using array explode(string $delimiter , string $string)) , and get the name of each one from vender_type table, try this :

$VenderData = Vender::where('active', '=', '1')->get();
foreach($VenderData as $vend)
{
     $vend->new_type = array();
     $types = explode(",", $vend->type);
     foreach($types as $type)
     { 
         $t = vender_type::where('code', $type)->first();
         if($t)
             $vend->name_type[] = $t->name;
             // or for example : $vend->name_type[$type] = $t->name;
     }
}

I hope that will help you.

Comments