Collection hook
This is the official documentation of the forestadmin/laravel-forestadmin v2+ and forestadmin/symfony-forestadmin PHP agents.
Forest Admin allows customizing at a very low level the behavior of any given Collection via the usage of Collection Hooks.
How it works
Any given Collection should implement all of the following functions:
listcreateupdatedeleteaggregate
The Collection Hooks feature allows executing code before and/or after any of these functions, providing an easy way to interact with your Collections.
To declare a Hook on a Collection, the following information is required:
A lifecycle position (
Before|After)An action type (
List|Create|Update|Delete|Aggregate)A callback, that will receive a context matching the provided hook position and hook definition.
Context object reference
All hook contexts provide access to:
getCollection()- the current collection, which can be queried using the Forest Admin Query InterfacegetDatasource()- the composite data source containing all collectionsgetCaller()- information about the user performing the operation
The caller object
caller objectThe caller object contains information about the current user:
getId()
User ID
getEmail()
User email
getFirstName()
First name
getLastName()
Last name
getTeam()
Team name
getRole()
Role name
getTags()
Custom tags
getTimezone()
User timezone
Error methods
All contexts provide methods to throw errors that will be displayed in the Forest Admin UI:
throwValidationError(message)
Display a validation error
throwForbiddenError(message)
Display a forbidden error
throwError(message)
Display a generic error
Hook-specific context properties
Each hook type provides additional properties:
List
Before
getFilter() (paginated filter), getProjection() (fields to return)
List
After
Same as Before + getRecords() (returned records)
Create
Before
getData() (data to create)
Create
After
getData() + getRecords() (created records)
Update
Before
getFilter(), getPatch() (read-only)
Update
After
getFilter(), getPatch() (read-only)
Delete
Before/After
getFilter() (filter for records to delete)
Aggregate
Before
getFilter(), getAggregation(), getLimit()
Aggregate
After
Same as Before + getAggregateResult()
A single Collection can have multiple Hooks with the same position and the same type. They will run in their declaration order. Collection Hooks are only called when the Collection function is contacted by the UI. This means that any usage of the Forest Admin query interface will not trigger them.
Basic use cases
In the following example, we want to prevent a set of users from updating any records of the Transactions table. We want to check if the user email is allowed to update a record via an external API call.
Another good example would be the following: Each time a new User is created in the database, I want to send him an email.
Advanced examples
Preventing deletion of protected records
Querying other collections via dataSource
Last updated
Was this helpful?