Pivot Filters
Overview
Pivot filters can be specified in two ways:
- on Custom Intermediate Table Models (
Pivot
,MorphPivot
). - on your main models (
Model
).
With Custom Intermediate Table Models
Added in 2.1.0
This is the recommended way
- Define the allowed pivot filters once in the Custom Intermediate Table Model.
- Not required to call
->pivot()
. - Caveat: Must call
->includeRelationFields()
onFilter::relation()
.
If you are utilising Custom Intermediate Table Models, you may define filters on that model.
Filters defined on this model will be applied to the intermediate table.
Restricting Allowed Pivot Filters.
Sometimes you may only want the pivot filter to be allowed when filtering by relationship one way but not the other way.
For example:
- Allowed when filtering
User
$has
Role
. - Denied when filtering
Role
$has
User
.
To achieve this you can specify the allowed “from” model for the pivot filter.
Without Custom Intermediate Table Models
If you are NOT utilising Custom Intermediate Table Models, you may define pivot filters on your main models.
Filter::field()
filters can be marked as pivot filters if you want the filter to be applied to a column on the intermediate table linking the models.
You must specify the parent model fqcn.
BelongsToMany
In the below example of class Post
and class Tag
.
- The pivot filter is specified in the
allowedFilters
method of both classes. - The pivot filter can only be used when in the context of the
posts
ortags
relationship.
Allowed
With the models setup as described above. The following filters are allowed.
DeniedFilterException
With the models setup as described above. The following filters are denied.
MorphToMany (Polymorphic)
When defining a pivot filter for MorphToMany
relations, you can specify a list of models in the ->pivot()
method.