I create function inside Model. Variable $category=1,2,3;
is string
I want that function to look in table categories and to return me name of this ids in one variable to be like $categoryName=first,second,third
public function getCategory($category){
$names = explode(",",$category);
foreach ($names as $name){
$categories = DB::table('categories')->where('id',$name)->first();
$categoryName = implode(',',(array)$categories->name);
}
return $this->$categoryName;
}
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
No need to loop over your ids and do multiple DB queries - you can get them all with just one query using whereIn
public function getCategory($category) {
$ids = explode(",",$category);
$categories = DB::table('categories')->whereIn('id',$ids)->get();
return $categories->implode('name', ',');
}
More info about whereIn in the docs.
However it would be neater to do this using Eloquent, the Laravel way, for example (this assumes you have a Category model to match your categories table):
public function getCategory($category) {
$ids = explode(",",$category);
$categories = App\Category::find($ids);
return $categories->implode('name', ',');
}
More info about retrieving models in the docs.