ICStudio
Services
PortfolioCase Studies
Tools
DemoBlog
ICStudio
HomeBlogFilter belongs-to-many in October CMS adminpanel

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.

Published: 11/15/2021

Якщо ви робите повноцінні рішення на базі OctoberCMS, то без фільтрів сутностей адміністративної панелі вам навряд чи обійтися. Навіть якщо ви їх не замислювали на етапі створення, десь перед запуском проекту, коли клієнт внесе свої численні дані в проект, питання управління цими даними стане досить гостро.

Документація October щодо створення фільтрів має умовний, поверхневий характер. Особливо це стосується зв'язків belongsToMany, коли крім самих моделей присутня pivot-таблиця. Давайте напишемо такий код самі.

Всі нестандартні вибірки з моделі в Laravel реалізуються через scope. Наприклад:

php
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();

        });
    }

Тоді отримати результат виконання цього запиту можна просто за допомогою ModelName::HomePageRecommend()

Аналогічним способом можна домогтися роботи фільтра у своїх плагінах для зв'язку типу belongsToMany. У config_filter.yaml додаємо:

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

З параметра scope стає зрозуміло, яку назву методу нам потрібно створити в моделі: scopeFilterCategories(). Давайте створимо його

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

Вуаля :)

Share:

Want to work with us?

Let's discuss your project and find the best solution

Contact us

Related Posts

10/16/2024

Why October CMS is the ideal choice for Creative Businesses and Businesses with non-standard business processes

10/14/2024

Online Payment Security: How to Protect Client Data in Your Laravel Project

5/17/2023

Pawnshop software: benefits, features, requirements

ICStudio

Professional web development and IT solutions for business

Quick Links

  • Home
  • Portfolio
  • Case Studies
  • Blog
  • Team

Resources

  • Tools
  • AI Chatbots
  • Demo
  • Docs
  • Pilot Program
  • Hire Us

Services

  • Web Development
  • E-commerce
  • CRM
  • Support

Contacts

  • hello@icstudio.online
  • +38 099 123 45 67
  • Kyiv, Ukraine

© 2026 IC Studio. All rights reserved.

Privacy PolicyTerms of ServiceService Terms