Overview
TheManagesOneToMany trait provides complete CRUD functionality for one-to-many (HasMany) relationships with support for:
- Reading related records with filtering, pagination, and sorting
- Creating related records through the relationship
- Updating related records
- Deleting related records
- Bulk operations for all mutation methods
- Excel/PDF export of related data
Ronu\RestGenericClass\Core\Traits\ManagesOneToMany
Location: /src/Core/Traits/ManagesOneToMany.php:32
Configuration
Basic Setup
Add the trait to your controller and define$oneToManyConfig:
Configuration Options
Required
relationship(string) - Name of the HasMany method on the parent modelrelatedModel(string) - Fully qualified class name of the related modelparentModel(string) - Parent model class nameforeignKey(string) - Foreign key column in the related tablelocalKey(string) - Primary key column in the parent table
Optional (mutation)
dataKey(array|string) - Request keys to extract data from (default:[])deleteRelated(bool) - Delete related model ondeleteRelation(default:true)
Read Operations
listRelation
List related entities with filtering, pagination, and sorting.Parameters
Request $request- HTTP request with query parametersmixed $parentId- Parent ID (null = auth user)
Query Parameters
select- Columns to select (default:['*'])relations- Relations to eager-loadeq/attr- Equality filtersoper- Complex filters (see Filtering)orderby- Sort orderpagination- Pagination settings
Example
showRelation
Retrieve a single related entity.Parameters
Request $request- HTTP requestmixed $parentIdOrRelatedId- Parent ID (admin) or related ID (site/mobile)mixed $relatedId- Related ID (admin only)
Route Shapes
Returns
- Related model instance on success
- 404 JSON response if not found
Example Response (Not Found)
Create Operations
createRelation
Create new related entities through the relationship.Single Mode
Route:POST /countries/1/states
Request:
Bulk Mode
Set_scenario to any value containing “bulk”:
Route: POST /countries/1/states?_scenario=bulk_create
Request:
The foreign key (
country_id) is automatically set by Laravel’s relationship.Update Operations
updateRelation
Update related entities.Single Mode
Route:PUT /countries/1/states/5
Request:
Bulk Mode
Route:PUT /countries/1/states?_scenario=bulk_update
Request:
Bulk Partial Failure
If some IDs are not found:Delete Operations
deleteRelation
Delete related entities.Configuration
Single Mode
Route:DELETE /countries/1/states/5
Response:
Bulk Mode
Route:DELETE /countries/1/states?_scenario=bulk_delete
Request:
Export Operations
exportRelationExcel
Export related data to Excel.Parameters
filename(string) - Output filename (default:'export.xlsx')columns(array|CSV) - Explicit columns for spreadsheetselect,eq,oper,orderby,relations- Same aslistRelation
Example
maatwebsite/excel package
exportRelationPdf
Export related data to PDF.Parameters
filename(string) - Output filename (default:'export.pdf')template(string) - Blade view name (default:'pdf')columns,select,eq,oper,orderby,relations- Same aslistRelation
Example
barryvdh/laravel-dompdf package
Internal Methods
resolveRelationConfig (Protected)
Resolves relation configuration from$oneToManyConfig.
Throws
BadRequestHttpException if relation is not configured
resolveParentEntity (Protected)
Resolves parent entity from ID or auth user.Throws
NotFoundHttpException if parent is not found or auth user is missing
extractMutationData (Protected)
Extracts mutation data from request body usingdataKey configuration.
executeMutation (Protected)
Wraps mutation operations in a database transaction with error logging.Parameters
Request $request- HTTP requestcallable $operation- Closure containing mutation logicint $status- HTTP status code on success (default: 200, use 201 for create)
Returns
JsonResponse - Operation result or error response
isBulkScenario (Protected)
Checks if the current request is a bulk operation.true if _scenario contains “bulk”.
Query Application Methods
applyOneToManyEqFilters (Protected)
Applies equality filters to the query.applyOneToManyOperFilters (Protected)
Applies complex operator-based filters.applyOneToManyOrdering (Protected)
Applies ordering to the query.applyOneToManySingleCondition (Protected)
Parses and applies a single filter condition.=, !=, <, >, <=, >=, like, not like, ilike, not ilike, in, not in, between, not between, null, not null.
Error Handling
Not Found (Single)
Returns 404 JSON:Not Found (Bulk)
Partial success with error details:Relation Not Configured
Parent Not Found
Transaction Rollback
On any exception during mutation, the transaction is rolled back and the error is logged:Query Optimization
The trait implements several optimizations:- Batch loading: Bulk operations load all entities in one query
- Batch deletes: Uses single
whereIn()->delete()for multiple IDs - Batch refresh: Refreshes all updated entities in one query
- Minimal queries: Typical bulk update = 3 queries (load, N updates, refresh)
Performance Considerations
- Use bulk operations when updating multiple records
- Eager-load relations to avoid N+1 queries
- Select only needed fields to reduce data transfer
- Add database indexes on foreign keys
- Paginate large result sets to avoid memory issues
Example Controller
Complete example:Related Documentation
- ManagesManyToMany Trait - Many-to-many operations
- Relation Loading - Eager-loading relations
- Dynamic Filtering - Filter related data
- Bulk Operations Guide - Bulk CRUD examples