Overview
BaseModel extends Laravel’s Eloquent Model with advanced features including:
- Validation: Built-in validation with scenario support (create/update)
- Hierarchy: Self-referencing tree structures with ancestor/descendant traversal
- Role-based field restrictions: Control field access per Spatie role
- Parent model support: Single Table Inheritance (STI) pattern
- MongoDB relations: Custom relation helpers for MongoDB connections
All models in your application should extend
BaseModel to leverage these features.Constants
MODEL
columns
RELATIONS
PARENT
HIERARCHY_FIELD_ID
parent_id, manager_id).
Example:
Properties
fieldsByRole
array<string, list<string>>
default:"[]"
Maps role names to arrays of privileged field names
- Fields NOT listed are writable by any authenticated user
- Superusers bypass all restrictions
- Multiple roles grant union of field access
scenario
create or update). Used for context-aware validation.
fieldKeyUpdate
Key Methods
getDeniedFieldsForUser()
mixed
required
The authenticated user model (must have Spatie’s
hasRole() method)list<string>
Array of field names the user cannot write
- If
$fieldsByRoleis empty → return[](no restrictions) - If user has
is_superuser = true→ return[] - Build universe of all privileged fields
- Build allowed set from user’s roles
- Return universe − allowed
Accessor Methods
getPrimaryKey()
getFieldKeyUpdate()
getScenario()
create or update).
setScenario()
Hierarchy Methods
hasHierarchy()
PARENT defined).
hasHierarchyField()
getHierarchyFieldId()
parent_id).
hierarchyParent()
hierarchyChildren()
isHierarchyRoot()
getHierarchyAncestors()
getHierarchyDescendants()
int|null
default:"null"
Maximum depth to traverse (null = unlimited)
int
default:"0"
Current depth in recursion (internal use)
Validation Methods
rules()
self_validate()
string
default:"create"
Validation scenario (
create or update)bool
default:"false"
If true, only validate fields present in attributes
bool
default:"true"
Include primary key in validation
array
validate_all()
array
required
Data to validate
string
default:"create"
Validation scenario
array
save_model()
array
default:"[]"
Attributes to save (uses current attributes if empty)
string
default:"create"
Operation scenario
array
Static Methods
create_model()
update_multiple()
destroy_model()
array
MongoDB Relation Methods
These methods enable relationships between SQL and MongoDB databases.
belongsToMongo()
hasManyMongo()
hasOneMongo()
Usage Example
Related
BaseService
Service layer with query building and CRUD operations
RestController
Controller exposing RESTful API endpoints