Relation Configuration
Before you can load relations through the API, they must be declared in your model’sRELATIONS constant.
Security Whitelist
TheRELATIONS constant acts as a security whitelist:
Product.php
Why Whitelist Relations?
- Security: Prevents exposure of sensitive relationships
- Performance: Limits accidental eager loading of expensive relations
- API Design: Explicitly defines your public API surface
Basic Relation Loading
Load All Fields
Load complete related models:Load Multiple Relations
The “all” Shortcut
Load all allowed relations at once:This loads every relation in
RELATIONS. Use cautiously on models with many relations or large datasets.Field Selection in Relations
Reduce payload size by selecting only needed fields from relations.Syntax
Use the colon syntax:"relation:field1,field2,field3"
Foreign Key Auto-Inclusion
The package automatically includes foreign keys to maintain relationships:name was requested, the foreign key category_id is automatically included:
Always include the primary key (
id) in your selection. It’s required for relationship mapping.Multiple Relations with Fields
Nested Relations
Load relations of relations using dot notation.Two Levels Deep
Nested with Field Selection
parent relation:
Three Levels Deep
Relation Validation
The package validates all relation paths to prevent typos and unauthorized access.Invalid Relation Error
Request:Strict Validation Mode
By default, models must explicitly defineRELATIONS:
config/rest-generic-class.php
strict_relations=true, models without RELATIONS will throw an error:
Combining Relations with Filtering
Relation loading and filtering work together seamlessly.Load Relations on Filtered Results
- Filters products (status=active AND price>=50)
- Eager-loads category and supplier for matching products
Filter by Relation Properties
Filter the root query based on related data:- With status=active
- That belong to a category with “electronics” in the name
- With the category data eager-loaded
Filtering Eager-Loaded Relations
Use_nested=true to filter the relations themselves, not just the root query.
Without _nested (Default)
- Returns products that have reviews with rating >= 4
- Loads all reviews for those products (including ratings < 4)
With _nested=true
- Returns products that have reviews with rating >= 4
- Loads only reviews with rating >= 4
With
_nested=true, the eager-loaded reviews array will only contain filtered items. This changes your response structure.Optimizing N+1 Queries
N+1 queries occur when you load a list of records, then query for related data inside a loop.The Problem
Without eager loading:The Solution
With eager loading:Monitoring Query Count
Enable query logging to verify eager loading:.env
storage/logs/rest-generic-class.log for executed queries.
Polymorphic Relations
Rest Generic Class supports polymorphic relations with proper configuration.Setup
Comment.php
Product.php
Loading Polymorphic Relations
Real-World Examples
E-commerce: Product Listing with Category and Reviews
CRM: Leads with Assigned User and Company
Blog: Posts with Author, Category, and Comment Count
Troubleshooting
Relation Not Loaded
Symptom: Relation isnull or missing from response
Causes:
- Relation not in
RELATIONSconstant - Typo in relation name
- Foreign key is null
- Verify:
php artisan tinker→Product::RELATIONS - Check raw data:
GET /api/v1/products(without relations param) - Look for null foreign keys
Wrong Fields in Relation
Symptom: Relation includes fields you didn’t select Cause: Foreign key auto-inclusion Explanation: The package adds foreign keys automatically to maintain relationships. This is intentional.Performance Issues
Symptom: Slow response times with relations Causes:- Loading too many relations
- Large collections without pagination
- Missing database indexes on foreign keys
- Load only needed fields:
category:id,name - Always paginate large datasets
- Add indexes:
$table->index('category_id')
Next Steps
Advanced Filtering
Learn to combine relation loading with complex filters
Hierarchical Data
Work with self-referencing tree structures
Many-to-Many
Manage pivot tables and attach/detach operations
Caching
Cache relation queries for better performance
Evidence
-
File:
src/Core/Services/BaseService.php
Lines: 98-174, 176-224
Implementsrelations()method with field selection, validation, and_nestedsupport -
File:
src/Core/Services/BaseService.php
Lines: 1334-1395, 1397-1438
ShowsgetRelationsForModel()andextractRelationFiltersForModel()for validation -
File:
src/Core/Models/BaseModel.php
Lines: 40-44
DefinesRELATIONSconstant used for whitelisting