Overview
Rest Generic Class provides powerful relation loading capabilities that allow clients to:- Eager-load relationships with the
relationsparameter - Select specific fields from relations
- Filter and sort related data
- Nest relations multiple levels deep
- Load pivot data for many-to-many relationships
Basic Relation Loading
Declaring Relations
First, declare allowed relations in your model:Loading Relations
Load relations via therelations query parameter:
Field Selection
Select Specific Fields
Limit fields from relations:id and name from category, and rating and comment from reviews.
The primary key is always included automatically, even if not specified.
Combine with Main Model Selection
Nested Relations
Loading Multi-Level Relations
Load relations of relations using dot notation:Deep Nesting Example
Filtering Related Data
Filter on Relation Fields
Use the_nested parameter to apply oper filters to relations:
WhereHas Conditions
Filter parent records based on related data:Complex Nested Filters
Relation Types
One-to-Many (HasMany)
Many-to-One (BelongsTo)
Many-to-Many (BelongsToMany)
Has-One-Through and Has-Many-Through
Polymorphic Relations
Advanced Scenarios
Conditional Relations
Load different relations based on user role:Counting Relations
UsewithCount() for relation counts:
Aggregate Functions
Load computed values:Relation Management Traits
Rest Generic Class provides traits for managing related records:ManagesOneToMany
Provides CRUD endpoints for HasMany relationships:ManagesManyToMany
Provides CRUD endpoints for BelongsToMany relationships:Configuration
Configure relation behavior inconfig/rest-generic-class.php:
Performance Optimization
Eager Loading vs Lazy Loading
Good - Eager load to avoid N+1 queries:Select Only Needed Fields
Limit Relation Depth
Avoid deeply nested relations in production:Error Handling
Common relation errors:Security Best Practices
Example permission check:Related Documentation
- Dynamic Filtering - Filter related data
- ManagesOneToMany Trait - One-to-many CRUD
- ManagesManyToMany Trait - Many-to-many CRUD
- Relation Loading Guide - Detailed examples