So ... I got those two eloquent models and a pivot table:
## Categories ##
- ID
- title
belongsToMany(Items)
## Items ##
- ID
- title
belongsToMany(Categories)
## Items_Categories ##
- items ID
- categories ID
I need a list of ALL items and highlight those which are in a given category.
# Example #
## Categorie #1 ##
- Item #1 (is in category)
- Item #2
- Item #3 (is in category)
- Item #4 (is in category)
- Item #5
## Category #2 ##
- Item #1 (is in category)
- Item #2
- Item #3
- Item #4 (is in category)
- Item #5
I feeld like I did this a hundred times in the past, but I can't figure out how to set this up. :-(
If there's a better solution on setting up those models / relationships I'm game.
// Get a single category with containing items
$category = Catgegory::whereNull('is_deleted')
->where('id', 1)
->with('items')
->first();
// Get all items
$allItems = Item::whereNull('is_deleted')
->get();
// Now what?
foreach ($allItems as $item) {
// Compare with category items?!
}
You can add a method in items model to check whether is item category equals to that category or not. so you can check it like so:
The method in the item model that checks the category_id:
public function isInCategory($category_id){
//get all $category_ids
$category_ids = $this->categories()->pluck('id')->toArray();
//check if $category_id exists in $category_ids array
if(is_array($category_ids) && in_array($category_id,$category_ids))
return true;
return false;
}
Or you can do it with this method
public function isInCategory($category_id){
return $this->categories->contains($category_id);
}
Both methods are working fine. But remember to write this method in Item model.
So you can use it in your code like this:
// Get a single category with containing items
$category = Catgegory::whereNull('is_deleted')
->where('id', 1)
->with('items')
->first();
// Get all items
$allItems = Item::whereNull('is_deleted')
->get();
// check the category id
foreach ($allItems as $item) {
$item->isInCategory($category->id) // returns true or false
}