Filling Properties from a Route Parameter
When creating data objects from requests, it’s possible to automatically fill data properties from request route parameters, such as route models. TheFromRouteParameter attribute allows filling properties with route parameter values.
Using Scalar Route Parameters
$id property will be filled with the songId route parameter value (which most likely is a string or integer).
Using Models, Objects or Arrays as Route Parameters
Given that we have a route to create songs for a specific author, and that the{author} route parameter uses route model binding to automatically bind to an Author model:
$artist property will be filled with the artist route parameter value, which will be an instance of the Artist model. Note that the package will automatically cast the model to ArtistData.
Filling Properties from Route Parameter Properties
TheFromRouteParameterProperty attribute allows filling properties with values from route parameter properties. The main difference from FromRouteParameter is that the former uses the full route parameter value, while FromRouteParameterProperty uses a single property from the route parameter.
In the example below, we’re using route model binding. {song} represents an instance of the Song model. FromRouteParameterProperty automatically attempts to fill the SongData $id property from $song->id:
Using Custom Property Mapping
In the example below,$name property will be filled with $song->title (instead of $song->name):
Nested Property Mapping
Nested properties are supported as well. Here, we fill$singerName from $artist->leadSinger->name:
Route Parameters Take Priority Over Request Body
By default, route parameters take priority over values in the request body. For example, when the song ID is present in the route model as well as request body, the ID from route model is used:$id will be 123 even though the request body has 321 as the ID value.
Allowing Request Body to Override Route Parameters
The above behavior can be turned off by switching thereplaceWhenPresentInPayload flag off. This can be useful when you intend to allow updating a property that is present in a route parameter, such as a slug:
$slug will be never-gonna-give-you-up even though the route parameter value is never.
Filling Properties from the Authenticated User
TheFromAuthenticatedUser attribute allows filling properties with values from the authenticated user:
FromAuthenticatedUserProperty:
Filling Properties from the Container
TheFromContainer attribute allows filling properties with dependencies from the container:
FromContainerProperty:
Creating Your Own Injectable Attributes
All the attributes we saw earlier implement theInjectsPropertyValue interface:
resolve method is responsible for returning the value that should be injected into the property. The shouldBeReplacedWhenPresentInPayload method should return true if the value should be replaced when present in the payload.