Simply, what you want to do can be done as following.
public function getCategory($categoryIds) // ex) 1,2,3
{
$categoryIdArray = explode(",", $categoryIds); // [1,2,3]
$categoryName = '';
foreach ($categoryIdArray as $categoryId){
$category = DB::table('categories')->where('id',$categoryId)->first();
$categoryName .= $category->name . ',';
}
$categoryName = substr($categoryName, 0, -1);
return $categoryName;
}
However, the example above don't make use of the advantage of Model
.
Does the Model
which have getCategory
method have category_ids
attribute?
If it is, you can write as follows.
public function getCategory()
{
$categoryIdArray = explode(",", $this->category_ids);
$categoryName = '';
foreach ($categoryIdArray as $categoryId){
$category = DB::table('categories')->where('id',$categoryId)->first();
$categoryName .= $category->name . ',';
}
$categoryName = substr($categoryName, 0, -1);
return $categoryName;
}
You can access category_ids
which have 1,2,3
value for instance via $this
so it doesn't need argument
.
To do moreover effectively, you can have category_id
attribute in another model.
In that case, you can do above more simply.
Reference:
https://laravel.com/docs/5.4/eloquent-relationships#many-to-many