Get related categories

I have a collection of “project” pages that are siblings under “projects” Each project has a multiselect category field, e.g. a “project” could have Architecture, Interior design as selected categories.

In my “projects” controller I have the following logic:

// get all categories
$categories = $page->children()->pluck('category', ',' ,true);

The “projects” page can also have a category parameter in it’s url, which I catch with the following logic:

// filter projects by category
if($category = param('category')) {
    $projects = $projects->filterBy('category', $category, ',');
}

In the case of a category parameter being present in the url I want to create an array of “related” categories (categories that also belong to projects which have the parameter category). I can do that with:

// get related categories of selected category
$relatedCategories = $page->children()->filterBy('category', $category, ',')->pluck('category', ',' ,true);

The above works but doesn’t exclude the selected category from the array $relatedCategories. Therefore I would like to exclude the selected category from $relatedCategories. I tried using remove() like that:

$relatedSectors->remove($sector);

,but I get the error message “Call to a member function remove() on array”

Any ideas why this happens or alternative ways would be appreciated.

Thanks so much.

First of all, let’s keep the code dry, instead of repeating the filter stuff:

Here’s one way of achieving this:

$relatedCategories = []
if($category = param('category')) {
    $projects = $projects->filterBy('category', $category, ',');
    $relatedCategories = $projects->pluck('category', ',', true);
    if ($key = array_search($category, $relatedCategories)) {
        unset($relatedCategories[$key]);
    }
}

dump($relatedCategories);

Yes, it means what is says. remove() is a method of the Collection class and its child classes, relatedCategories is an array, so you can’t call this method on an array but only on “members” (instances) of the Collection class.

Thanks a lot. unset did the trick for now. Will also look into avoiding repetitions.

Ok. Totally confused Collections with Arrays.