Reputation: 3440
So basically I have an array mutator which works perfectly, but the field its pulling is only a char 1 and only 1 entry so it works fine
However I want to do the exact same thing with a field that contains multiple entries by a comma separator. below is what i have that works and and example of what I want.
The field interests contains a number from 1 to 3,
protected $userTypes = array(
'1' => 'Owner',
'2' => 'Admin',
'3' => 'Standard User'
);
public function getUserTypeAttribute($value)
{
return $this->userTypes[$value];
}
now I have another field lets call it, InterestList but it has multiple entries separated by commas like so 3,4,5,6,7
How would I get the code like above to work for something like that?
Upvotes: 1
Views: 649
Reputation: 3440
Hey so I ended up with an answer, Below is the code
public function getInterestsAttribute($value)
{
$InterestList = array(
'1' => 'Books',
'2' => 'Cars',
'3' => 'Cats'
);
$strExplode = explode(",",$value);
foreach ($strExplode as $i=>$ANUMBER){
echo $InterestList[$ANUMBER];
}
}
Then in the blade you just go about your way as normal. eg.
{{ $UserProfile->Interests }}
Upvotes: 0
Reputation: 1561
Try this --
<?php
// lets define the interest list
protected $interestList = array(
'1' => 'Play',
'2' => 'Sing',
'3' => 'Hobby'
);
// function for getting the interesttype strings
public function getIntestetTypeString($intStr=''){
// $intStr = '1,3' ; may be something like
$interestList = '';
if(!empty($intStr)){
$attrToIterate = explode(", ",$intStr) ;
foreach($attrToIterate as $value){
if($interestList){
$interestList .= ','. $this->interestList[$value] ;
}else{
$interestList .= $this->interestList[$value] ;
}
}
}
return $interestList ;
}
Upvotes: 1