๐งช Basic Features
๐งช Advanced Features
Expansion
The Expansion feature in Tuner allows API consumers to include related models directly in the response.
This removes the need for multiple requests and gives clients more control over the data they need.
Supported Relationships
Tuner supports all common Eloquent relationship types:
- HasOne
- HasMany
- BelongsTo
- BelongsToMany
Setup
By default, expansion is disabled.
To enable it, you need to define the getExpandableRelations
method in your model and provide relation settings.
Example
class User extends Model
{
public function phone() // <-- relation name
{
return $this->hasOne(Phone::class);
}
protected function getExpandableRelations(): array
{
return [
'phone' => [ // <-- relation name
'options' => [
'projectable_columns' => ['*'],
'sortable_columns' => ['*'],
'searchable_columns' => ['*'],
'filterable_columns' => ['*'],
],
'table' => 'phones', // optional
'fk' => 'user_id', // optional
],
];
}
}
Explanation:
- phone โ The relation name (must match your Eloquent relationship method).
- options โ Defines which modifiers can be applied on this relation.
- table โ (Optional) Explicitly specify the related table.
- fk โ (Optional) Explicitly specify the foreign key.
Usage
You can use the expand
modifier to load related resources.
When expanding, you can assign an alias to the relation.
This alias is required if you want to apply other modifiers such as columns
, sort
, or filter
.
Example
GET /api/users?expand[posts]=p&p_columns=id,title
Explanation:
- expand โ The modifier used to expand relationships.
- posts โ The relation of the subject (users) into the object resource (posts).
- p โ The alias assigned to the relation.
- p_columns โ Alias(p) + Separator(_) + Modifier(columns) (in this case, projection with columns).
The response will only include the id and title fields from the expanded posts relation.
Combining with Modifiers
Expansion works seamlessly with other Tuner modifiers:
Sort (sort)
GET /api/users?expand[posts]=p&p_sort[created_at]=desc
Search (search)
GET /api/users?expand[posts]=p&p_search[title]=*hello*
Filter (filter, in, between)
GET /api/users?expand[posts]=p&p_filter[status]=published
GET /api/users?expand[posts]=p&p_in[id]=1,2,3
GET /api/users?expand[posts]=p&p_between[created_at]=2000-01-01,2010-01-01
Supported Operators
Expansion supports the same operators as other modifiers:
- Relational operators: =, <>, <, >, <=, >=
- Logical operators: AND, OR, AND!, OR!
Best Practices
- Use expansion only for the data you really need. Over-expanding can impact performance.
- Always provide an alias when you plan to apply other modifiers (columns, sort, filter).
- Combine columns with expand to keep responses lightweight.
- Sort and filter expanded relationships carefully to avoid unexpected results.
Expansion makes your APIs smarter and more consumer-friendly โ clients can tune the exact shape of the response they want.