Skip to content

Backend

Reference for every PHP layer that ships with Modularous. Sections below are ordered alphabetically — each one points at the directory under src/ it documents and the matching reference page under system-reference/backend/.

SectionSource pathReference
Activatorssrc/Activators/Activators →
Brokerssrc/Brokers/Brokers →
Console Commandssrc/Console/Console guide →
Controllerssrc/Http/Controllers/Controllers →
Entitiessrc/Entities/Entities →
Entity Traitssrc/Entities/Traits/Entity Traits →
Events & Listenerssrc/Events/, src/Listeners/Events & Listeners →
Facadessrc/Facades/Facades →
Form Requestssrc/Http/Requests/Form Requests →
Generatorssrc/Generators/Generators →
Helperssrc/Helpers/Helpers →
Middlewaresrc/Http/Middleware/Middleware →
Notificationssrc/Notifications/Notifications →
Providerssrc/Providers/Providers →
Repository Traitssrc/Repositories/Traits/Repository Traits →
Scheduled Jobssrc/Schedulers/Scheduled Jobs →
Servicessrc/Services/Services →
Supportsrc/Support/Support →
View Composerssrc/Http/ViewComposers/View Composers →

Architecture at a glance

Modularous layers a Laravel package on top of nWidart/laravel-modules and adds a CRUD-aware admin pipeline that every module inherits. The backend is organised as a stack of composable layers — bootstrap on top, persistence at the bottom — with cross-cutting services sitting alongside.

┌──────────────────────────────────────────────────────────────────┐
│  Bootstrap        Providers · Activators · Facades · Helpers     │
│                   ──────────────────────────────────────────────  │
│  HTTP entry       Middleware → Form Requests → Controllers       │
│                   ──────────────────────────────────────────────  │
│  Domain           Repositories ↔ Repository Traits               │
│                   Entities ↔ Entity Traits                       │
│                   ──────────────────────────────────────────────  │
│  Reactions        Events → Listeners → Notifications             │
│                   ──────────────────────────────────────────────  │
│  Background       Scheduled Jobs · Console Commands              │
│                   ──────────────────────────────────────────────  │
│  Cross-cutting    Services · Support · View Composers · Brokers  │
│                   Generators (build-time only)                   │
└──────────────────────────────────────────────────────────────────┘

Typical request lifecycle

A normal admin CRUD request walks through most of these layers in order:

  1. ProvidersModularousProvider boots child providers (BaseServiceProvider, RouteServiceProvider, AuthServiceProvider, …) and binds every container entry the rest of the stack depends on.
  2. ActivatorsModularousActivator and ModuleActivator short-circuit the request if the target module or route is disabled.
  3. Middleware — the web / admin / api pipelines run guards (Authenticate, Authorization, Hostable, Language, Navigation, HandleInertiaRequests, …).
  4. Form Request — a BaseFormRequest subclass authorizes the user and validates input before the controller method runs.
  5. ControllerBaseController resolves the active route, applies traits (ManageIndexAjax, ManageInertia, ManagePrevious, ManageSingleton, ManageTranslations), renders the form schema, and delegates persistence to $this->repository.
  6. Repository (+ Traits) — the base Repository invokes every applicable repository trait (prepareFieldsBeforeSave{Trait}, afterSave{Trait}, …) around the Eloquent save().
  7. Entity (+ Traits) — Eloquent models compose entity traits for slugs, positions, soft-delete, translations, media, files, repeaters, blocks, processes, state, payments, presenters, and broadcasting context.
  8. Events & Listeners — model lifecycle and auth events fire; Listener::handle() resolves the matching {EventName}Notification and dispatches it when modularous.mail.enabled = true.
  9. View Composers — for Inertia/Blade responses, composers inject shared props (current user, navigation, uploader configs, localization, URLs).
  10. Response — Inertia/JSON/Blade payload returns to the client; broadcasted events propagate over Echo channels.

How the layers reference each other

If you are working on…You typically touch…
A new admin routeProvidersGeneratorsControllersForm RequestsEntitiesRepository Traits
Authentication / registrationMiddlewareControllers (Auth) → BrokersNotificationsEvents & Listeners
Caching / invalidationServices (ModularousCacheService, CacheRelationshipGraph) → Repository Traits (Logic) → Console Commands (cache:*)
File / media uploadsControllers (Filepond / FileLibrary / MediaLibrary) → Form RequestsServices (FilepondManager, FileLibrary, MediaLibrary, Uploader) → Entity Traits (HasFileponds, HasFiles, HasImages)
Multi-tenant routingProviders (RouteServiceProvider) → Support (HostRouting) → Middleware (Hostable) → Facades (HostRouting)
Real-time / chatEvents & ListenersNotificationsServices (BroadcastManager) → Scheduled Jobs (ChatableScheduler)

→ Architecture deep-dives also live under the system reference — cache, broadcasting, host routing, and module conventions are documented there.


Activators

Directory: src/Activators/ · Namespace: Unusualify\Modularous\Activators

Activators persist and resolve enable/disable state. Modularous splits activation into two layers — module-level (whether a module loads at all) and route-level (whether a specific route action inside a module is enabled).

ClassPersisted inPurpose
ModularousActivatormodules_statuses.json + cacheStores and resolves module-level statuses (enabled / disabled)
ModuleActivatorroutes_statuses.json per moduleStores and resolves route-level statuses inside a module

CLI integration: route:disable, route:enable, route:status read and mutate these files.

Activators reference


Brokers

Directory: src/Brokers/ · Namespace: Unusualify\Modularous\Brokers

Powers the email-verification-based registration flow behind the Register facade. Mirrors Laravel's password broker design, adapted for verification tokens.

ClassRole
RegisterBrokerExecutes verification-link and registration-token operations
RegisterBrokerManagerResolves named broker instances and selects the default broker
TokenRepositoryInterfaceContract for email-based token repository methods

Flow: controller → Register::broker()RegisterBrokerManagerRegisterBrokerTokenRepositoryInterface.

Brokers reference


Console Commands

Directory: src/Console/ · Namespace: Unusualify\Modularous\Console

Discovered via CommandDiscovery::discover() in BaseServiceProvider. Every command extends a BaseCommand, which adds module-aware option resolution and consistent output formatting on top of Illuminate\Console\Command.

CategoryPathCommands
CacheConsole/Cache/cache:clear, cache:list, cache:warm, cache:stats, cache:versions, cache:graph
CoverageConsole/Coverage/coverage:report, coverage:methods
DocsConsole/Docs/Docs scaffolding helpers
FlushConsole/Flush/flush, flush:filepond, flush:sessions
MakeConsole/Make/make:controller, make:controller-api, make:event, make:feature, make:input-hydrate, make:laravel-test, make:listener, make:migration, make:model, make:module, make:operation, make:repository, make:repository-trait, make:request, make:route, make:route-permissions, make:stubs, make:theme, make:vue-input, make:vue-test
MigrationConsole/Migration/migrate, migrate:refresh, migrate:rollback
ModuleConsole/Module/module:fix, module:remove, route:disable, route:enable, route:status
OperationsConsole/Operations/Workflow / batch-operation runners
SetupConsole/Setup/create-superadmin, create:database, install, setup:dev
SyncConsole/Sync/sync:states, sync:translations
Top-levelConsole/build, composer:merge, composer:scripts, db:check-collation, dev, pint, refresh, replace:regex, version
UpdateConsole/Update/Module-update commands

→ Per-command usage is documented in the Console guide.


Controllers

Directory: src/Http/Controllers/ · Namespace: Unusualify\Modularous\Http\Controllers

The controller hierarchy is CoreController → PanelController → BaseController. Modules extend BaseController and configure form schemas, with each layer adding more module-aware behaviour.

LayerPurpose
CoreControllerBase HTTP controller — shared response helpers
PanelControllerRoute/model resolution, index options, authorization, $this->repository
BaseControllerView prefix, form schema, index/create/edit flow, setupFormSchema()

BaseController traits: ManageIndexAjax, ManageInertia, ManagePrevious, ManageSingleton, ManageTranslations.

Request flow: preload()addWiths()setupFormSchema()index() / create() / edit()respondToIndexAjax() for AJAX.

Concrete controllers (selection): ApiController, ChatController, DashboardController, FileLibraryController, FilepondController, MediaLibraryController, MetricController, ProcessController, ProfileController, TagController, UiPreferencesController, plus auth-scoped controllers under Http/Controllers/Auth/.

Full Controllers reference


Entities

Directory: src/Entities/ · Namespace: Unusualify\Modularous\Entities

~30 Eloquent models for users, content, files, processes, state, and communication, plus supporting Casts/, Enums/, Interfaces/, Mutators/, Observers/, Scopes/, Traits/, and Translations/ subfolders. Module-generated models extend Model and gain soft-deletes, tagging, caching, presenter support, and trait composition out of the box.

GroupModelsReference
Base classesModel, RevisionModel → · Revision →
CommunicationChat, ChatMessageChat → · ChatMessage →
Content building blocksBlock, Repeater, Tag, TaggedBlock → · Repeater → · Tag →
Files & MediaFile, Filepond, Media, TemporaryFilepondFile → · Filepond → · Media →
OtherFeature, NestedsetCollection, RelatedItemFeature → · NestedsetCollection → · RelatedItem →
Process & WorkflowAssignment, Authorization, CreatorRecord, Process, ProcessHistoryAssignment → · Authorization → · Process →
State & DataSetting, Singleton, Spread, State, StateableSingleton → · State → · Stateable →
Users & AuthCompany, Profile, User, UserOauthCompany → · Profile → · User →

Enums: AssignmentStatus, PaymentStatus, Permission, ProcessStatus, RoleTeam, UserRole.

Full Entities reference


Entity Traits

Directory: src/Entities/Traits/ · Namespace: Unusualify\Modularous\Entities\Traits

A library of traits (top-level + nested under Auth/, Core/, Secondary/) covering relationships, accessors, scopes, lifecycle hooks, and broadcasting context. Each trait composes onto an entity to add a self-contained behaviour without subclassing.

GroupExamplesReference
AuthCanRegister, HasOauthAuth →
Core (top-level)HasPosition, HasPresenter, HasSlug, HasSpreadable, HasStateable, HasUuidCore →
MediaHasFileponds, HasFiles, HasImagesMedia →
Model behaviorHasPosition, HasPresenter, HasSlug, HasSpreadable, HasStateable, HasUuidModel behavior →
PaymentHasPayment, HasPriceablePayment →
ProcessesHasProcesses, ProcessableProcesses →
RelationshipsAssignable, Chatable, HasAuthorizable, HasCreatorRelationships →
RepeatersHasRepeatersRepeaters →
SecondaryHasBlocks, HasNesting, HasRelated, HasRevisionsSecondary →
SingletonsIsHostable, IsSingularSingletons →
TranslationHasTranslation, IsTranslatableTranslation →

Full Entity Traits reference


Events & Listeners

Directory: src/Events/, src/Listeners/ · Namespace: Unusualify\Modularous\Events, Unusualify\Modularous\Listeners

Events fire at lifecycle boundaries (model created/updated, user registered, state changed). Listeners react and, when mail is enabled, dispatch the matching notification.

ClassRolePage
ListenerAbstract base for listeners — resolves notification class from event nameClass reference
ModelEventAbstract base — composes EventChanges, EventStateable, EventUrls, EventUser traits and provides broadcasting defaultsClass reference
User eventsModularousUserRegistered, ModularousUserRegistering, ModularousUserVerification, VerifiedEmailRegisterAuth events

Event traits (under events/traits/): EventChanges, EventStateable, EventUrls, EventUser. Each is auto-set up in ModelEvent's constructor and its public properties are serialized into broadcast payloads.

Full Events reference → Real-time setup, Echo integration, testing, and troubleshooting are covered in the Broadcasting guide.


Facades

Directory: src/Facades/ · Namespace: Unusualify\Modularous\Facades

21 Laravel facades providing static-style access to bound services. Each facade aliases a container entry to a concrete service class.

Selected facades: Coverage, CurrencyExchange, Filepond, HostRouting, MigrationBackup, Modularous, ModularousCache, ModularousRoutes, ModularousVite, Navigation, Redirect, Register, RelationshipGraph, SiteSettings, SystemSettings, CmsSettings, Utm.

Settings deep-dive: Settings Services.

Full Facades reference


Form Requests

Directory: src/Http/Requests/ · Namespace: Unusualify\Modularous\Http\Requests

Form Request classes that validate, authorize, and shape incoming requests for module endpoints. Extend Laravel's FormRequest with module-aware authorization and translation hooks.

ClassPurpose
BaseFormRequestShared validation/authorization plumbing
FileRequestFile upload validation
MediaRequestMedia upload validation
OAuthRequestOAuth callback payload validation
RequestGeneric module-aware base form request
StorePermissionRequestPermission creation
StoreRoleRequestRole creation

Full Form Requests reference


Generators

Directory: src/Generators/ · Namespace: Unusualify\Modularous\Generators

Scaffolding engine behind make:* and make:route commands. Produces the full PHP and JS file set for new module routes plus test scaffolding for both backend and frontend.

Generator (abstract)                ← NwidartGenerator + ReplacementTrait
├── RouteGenerator                  ← full-stack route scaffolding (primary)
├── StubsGenerator                  ← stub-only regeneration (fix/patch)
├── VueTestGenerator                ← Vitest/Jest test scaffolding
└── LaravelTestGenerator            ← PHPUnit test scaffolding
GeneratorResponsibility
GeneratorAbstract base — module resolution, config path helpers
LaravelTestGeneratorPHPUnit Unit or Feature test scaffolding
RouteGeneratorFull set of files for a new module route (model, migration, controller, repository, request, translations, permissions)
StubsGeneratorSelective stub regeneration with only / except lists
VueTestGeneratorVue component / composable / utility / store test scaffolding

Full Generators reference


Helpers

Directory: src/Helpers/ · Namespace: global functions

15 PHP helper files exposing 100+ global functions. Loaded by Composer autoload, available everywhere.

FileWhat it covers
arrayArray shape transforms
columnColumn metadata helpers
componentFrontend component resolution
composerComposer JSON parsing
connectorExternal-service connector helpers
dbSchema introspection (hasColumn, hasIndex, etc.)
formatCurrency / date / number formatting
frontFrontend URL/asset helpers
i18nLocale and translation helpers
inputInput schema / hydrate helpers
mediaImage URL / disk resolution
migrationsMigration build helpers
modulemodularousConfig(), module_path(), currentModule()
routerRoute resolution helpers
sourcesModule path discovery

Full Helpers reference


Middleware

Directory: src/Http/Middleware/ · Namespace: Unusualify\Modularous\Http\Middleware

14 middleware classes registered via BaseServiceProvider and grouped into pipelines for admin, auth, and API routes.

MiddlewarePurpose
AuthenticateModularous-aware auth guard
AuthorizationPermission/role enforcement
CompanyRegistrationCompany onboarding gate
HandleInertiaRequestsInertia shared props
HostableHost-based routing resolution
ImpersonateUser impersonation gate
LanguageLocale resolution from URL/header
LoadLocalizedConfigLocale-specific config loading
LogRequest logging
NavigationSidebar nav assembly
RedirectIfAuthenticatedGuest-only routes
RedirectorConfigured redirect rules
TeamsPermissionTeam-aware permission resolution
UtmUTM parameter capture

Full Middleware reference


Notifications

Directory: src/Notifications/ · Namespace: Unusualify\Modularous\Notifications

GroupClassesPage
Auth notificationsEmailVerification, GeneratePasswordNotification, ResetPasswordNotificationAuth notifications →
Feature baseFeatureNotificationFeatureNotification →
System notifications11 system notification classes (model lifecycle, payments, assignments, chat, state changes)System notifications →

Notifications are dispatched by Listener::handle() when modularous.mail.enabled = true and the listener resolves a {EventName}Notification class.

Full Notifications reference


Providers

Directory: src/Providers/ · Namespace: Unusualify\Modularous\Providers

Service providers wire the package into the host Laravel app. Bind services, publish config, register routes, hook view composers, wire the scheduler, and discover commands.

ProviderRole
AuthServiceProviderModularous policies and gates
BaseServiceProviderCore bindings, command discovery, view composers, scheduler, middleware aliases
CoverageServiceProviderCoverage analyzer + commands binding
ModularousProviderTop-level provider — registers all child providers
ModuleServiceProviderPer-module provider auto-generated for each module
RouteServiceProviderModule route registration with host/permission groups
ServiceProviderAbstract base with config publishing helpers
TelescopeServiceProviderTelescope integration when present

Full Providers reference


Repository Traits

Directory: src/Repositories/Traits/ · Namespace: Unusualify\Modularous\Repositories\Traits

Repository traits extend the base Repository class with domain-specific persistence logic. While Entity Traits define model-level behaviour, repository traits handle how data flows in and out — form field hydration, after-save side effects, table filters, caching.

Every repository trait follows a naming convention that the base Repository discovers and invokes at the right lifecycle stage:

ConventionWhen called
setColumns{Trait}Boot — registers form input names this trait manages
prepareFieldsBeforeCreate{Trait}Before insert
prepareFieldsBeforeSave{Trait}Before any save
beforeSave{Trait} / afterSave{Trait}Around the Eloquent save() call
hydrate{Trait}Sets in-memory relationships before save (preview/validation)
getFormFields{Trait}Populates form fields when editing
afterDelete{Trait} / afterRestore{Trait}Soft-delete + restore hooks
filter{Trait} / order{Trait}Index query scopes / ordering
getTableFilters{Trait}Filter tab definitions for the data table UI
getFormActions{Trait}Form action button definitions
GroupPage
Content (Blocks, Repeaters)Content →
Logic helpers (caching, schema, query building)Logic →
Media (Files, Images, Filepond)Media →
OAuthOAuth →
PaymentPayment →
ProcessesProcesses →
RelationshipsRelationships →
StateState →

Full Repository Traits reference


Scheduled Jobs

Directory: src/Schedulers/ · Namespace: Unusualify\Modularous\Schedulers

Background jobs auto-discovered from src/Schedulers/*.php via CommandDiscovery and registered against Laravel's Schedule inside BaseServiceProvider::boot() (no Console\Kernel.php is required in the host app).

CommandClassCadencePurpose
modularous:fileponds:schedulerFilepondsSchedulerDailyCleans up orphaned temporary_fileponds rows + their files
modularous:scheduler:chatableChatableSchedulerEvery minuteAggregates unread chat messages and dispatches UnreadChatMessage notifications
telescope:prune(Laravel Telescope)DailyPrunes Telescope entries older than 168 hours

Both Modularous schedulers can also be run manually as Artisan commands. Output goes to the scheduler log channel; the host server only needs the standard * * * * * php artisan schedule:run cron entry.

Full Scheduled Jobs reference


Services

Directory: src/Services/ · Namespace: Unusualify\Modularous\Services

Bound in the service container; injected via constructor or accessed through their dedicated Facades. Each group has its own reference page.

GroupMembersPage
Cache concernsCacheHelpers, CacheInvalidation, CacheTagsCache Concerns →
Core servicesAssets, BroadcastManager, Connector, CoverageService, CurrencyExchangeService, FilepondManager, FileTranslation, MessageStage, MigrationBackup, ModularousCacheService, RedirectService, Translation, UtmParametersServices →
CurrencyNullCurrencyProvider, SystemPricingCurrencyProviderCurrency →
SettingsAbstractSingularSettingsService, SystemSettingsService, CmsSettingsService, SiteSettingsServiceSettings →
FileLibraryDisk, FileServiceFileLibrary →
MediaLibraryGlide, Imgix, Local, TwicPics driversMediaLibrary →
UploaderSignAzureUpload, SignS3Upload, SignUploadListenerUploader →
View servicesModularousNavigation, UComponent, UWidget, UWrapperView Services →

Cache support: CacheRelationshipGraph drives cross-entity cache invalidation. The CLI face is cache:graph.

Full Services reference


Support

Directory: src/Support/ · Namespace: Unusualify\Modularous\Support

Stateless utility classes used across the codebase for command discovery, schema parsing, route grouping, and host-based routing.

ClassPurpose
CommandDiscoveryScan glob paths and return instantiable Command FQCNs
CoverageAnalyzerParse Clover XML and report per-method coverage
DecomposersParse schema/relation/validation strings for generators
FileLoaderTranslation file loader with multi-path support
FinderResolve model/repository by table name or route name
HostRouting / HostRouteRegistrarMulti-tenant host-based route groups
Migrations\SchemaParserRender migration $table->… PHP from schema strings
ModularousRoutesRoute group options and middleware alias registration
ModularousViteVite integration for the Modularous asset manifest
RegexReplacementBatch regex find-and-replace across a directory tree

Full Support reference


View Composers

Directory: src/Http/ViewComposers/ · Namespace: Unusualify\Modularous\Http\ViewComposers

Inject shared variables into Blade / Inertia layouts. Wired in BaseServiceProvider::registerViewComposers().

ComposerViewsCondition
ActiveNavigationlayouts with sidebarAlways
CurrentUseradmin.*, {baseKey}::*enabled.users-management = true
FilesUploaderConfigmaster/app-inertia layoutsenabled.file-library = true
Localizationmaster/auth/app-inertia layoutsAlways
MediasUploaderConfigmaster/app-inertia layoutsenabled.media-library = true
Urls*Always

Full View Composers reference


Cross-cutting concerns

A few capabilities don't live in a single section — they thread through several layers at once. Subsections below are ordered alphabetically; use them as a map to find every place a given concern shows up.

Authentication, authorization & registration

Auth is split between the request pipeline (middleware), the Spatie permission stack (gates/policies), and a verification-token broker for self-service registration.

LayerComponent
BrokersRegisterBroker, RegisterBrokerManager, TokenRepositoryInterface
ControllersHttp/Controllers/Auth/*
Entities & TraitsCompany, Profile, User, UserOauth; CanRegister, HasOauth
EnumsPermission, RoleTeam, UserRole
Form RequestsOAuthRequest, StorePermissionRequest, StoreRoleRequest
MiddlewareAuthenticate, Authorization, CompanyRegistration, Impersonate, RedirectIfAuthenticated, TeamsPermission
NotificationsEmailVerification, GeneratePasswordNotification, ResetPasswordNotification
ProvidersAuthServiceProvider

Caching

Modularous ships a versioned, tag-aware cache built on top of Laravel's cache. Invalidation propagates through a relationship graph so editing a model also flushes anything that depends on it.

LayerComponent
Bind / bootBaseServiceProvider (registers ModularousCacheService, CacheRelationshipGraph)
CLIcache:clear, cache:graph, cache:list, cache:stats, cache:versions, cache:warm
ConcernsCacheHelpers, CacheInvalidation, CacheTags
Day-to-day APIModularousCache facade, CacheRelationshipGraph
Repository hooksRepository Traits → Logic (afterSave{Trait}, afterDelete{Trait})

→ Full deep-dive: ModularousCacheService.

File & media uploads

Three independent upload pipelines share the same general shape (Form Request → Service → Entity Trait).

PipelineControllerServiceEntity TraitRepository Trait
Direct cloud uploadsUploader (SignAzureUpload, SignS3Upload)
File libraryFileLibraryControllerFileLibraryHasFilesMedia
Filepond (chunked uploads)FilepondControllerFilepondManagerHasFilepondsMedia
Media library (image variants)MediaLibraryControllerMediaLibraryHasImagesMedia

Module scaffolding & generation

Build-time only — these run from the CLI to produce or regenerate code.

LayerComponent
CLImake:* commands (Console Commands)
GeneratorsGenerator, LaravelTestGenerator, RouteGenerator, StubsGenerator, VueTestGenerator
SupportDecomposers, Migrations\SchemaParser, RegexReplacement

→ End-to-end walkthrough: Modules reference.

Multi-tenant / host-based routing

When the same module needs to serve different domains with different middleware or permission groups.

LayerComponent
Entity TraitsIsHostable, IsSingular
FacadeHostRouting
MiddlewareHostable
ProviderRouteServiceProvider
SupportHostRouting / HostRouteRegistrar, ModularousRoutes

Real-time broadcasting

Model lifecycle and chat events broadcast over Laravel Echo when broadcasting is enabled.

LayerComponent
Base classesListener, ModelEvent (with event traits)
Entity TraitsChatable, HasProcesses, HasStateable, Processable
NotificationsSystem notifications (model lifecycle, payments, assignments, chat, state changes)
Scheduled jobChatableScheduler
ServiceBroadcastManager

→ Setup, channel naming, Echo client, testing, and troubleshooting: Broadcasting guide.


→ Looking for something not covered above? Browse the system reference index or jump straight into the per-section overview pages linked from each heading.