[8.x] Add trait for models to detect their api resources and add some resource sugar #35515
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Borrowing from the new factory syntax, this PR adds a trait which can be added to models to detect the model's api resource. It also adds sugar around generating resource objects, both for single model instances and a collection of models.
This is based on an idea I added last week. I haven't added all the features (basically just alternative resource "states") that I mention in the idea issue, but the sugar is achieve while not introducing any breaking changes to the current way of creating resources.
By adding the
Illuminate\Http\Resources\HasResource
to a model, the resource can be created by using a few different fluent syntaxes.Say we have a
Post
model:And assume we have a
PostResource
object found in the typicalApp\Http\Resources
namespace (this supports the naming convention ofApp\Http\Resources\Post
orApp\Http\Resources\PostResource
, it looks for the existence of either):We can now create the resource without referencing the resource class directly:
This supports collections of models:
Some additional tests are needed before coverage is adequate.