Filter belongs-to-many in October CMS adminpanel

If you do full-fledged OctoberCMS-based solutions, you can hardly do without entity filters in the administrative panel. Even if you didn't think of them at the creation stage, sometime just before the launch of the project, when the client enters his numerous data into the project, the issue of managing this data will become quite acute.

The documentation on creating filters is tentative and superficial. This is especially true when you have a pivot table in addition to the models themselves. Let's write such code ourselves.

All non-standard selections from Models in Laravel are implemented through scope. For example:


public function scopeHomePageRecommend($query)
{
$current_cite_sity = config('app.current_site_city');

return \Cache::remember('home_page_recommend', 3600, function() use ($query, $current_cite_sity) {

return $query->where('city_id', $current_cite_sity)->where('is_recommend', 1)->with('image', 'gallery')->take(3)->get()->toArray();

});
}
 


Then you can simply get the result of this query via ModelName::HomePageRecommend()
In the same way you can get filter working in your plugins for belongsToMany type relation. In config_filter.yaml we add:

category:
label: Категория
modelClass: Path\To\Your\Model
scope: FilterCategories
nameFrom: name


From the scope parameter it becomes clear what method name we need to create in the model: scopeFilterCategories(). Let's create it


public function scopeFilterCategories($query, $categories)
{
return $query->whereHas('categories', function($q) use ($categories) {
$q->withoutGlobalScope(NestedTreeScope::class)->whereIn('id', $categories);
});
}

It's never too late to change your business for the better

Get start

This site uses cookies. We do not personalize you, but only make surfing the site more convenient. You can check out our Privacy Policy