Tip 2: Treat properties edited independently as separate resources #2
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.
The next custom action I'd like to look at is
PodcastsController@updateCoverImage
.Here's the endpoint:
If we want to remodel this custom action as a standard REST action, what should our endpoint be and what controller should we use?
Evaluating against our list of REST actions:
...it seems like "update" is probably our best choice, but what is the resource we are updating?
If you look at the current implementation, you can see that all we are really doing is updating a field on the
podcasts
table:You might think that what we are doing here is an "update" action against our
podcasts
resource, but similar to our nested resource example, we already have an "update" action for podcasts:This action is used to update the basic fields for a podcast, and is exposed through a completely separate form in the UI than
updateCoverImage
.We could try to piggy back off of this action, but remember, we don't want to re-use a single controller action for multiple user actions otherwise we risk introducing more complexity into our controller.
So what should we do?
✅ Create a dedicated
PodcastCoverImageController
Resources exposed through your controllers and endpoints don't have to map one-to-one with your models or database tables.
If a user edits one part of model using a different form than another part of a model, you should probably expose it as it's own resource.
So instead of making a
POST
request toupdate-cover-image
, lets make aPUT
request that treats the cover image like it's own resource:Once we create that new controller and move the old
PodcastsController@updateCoverImage
action over toPodcastCoverImageController@update
, we're left with the following controllers:PodcastsController
, with 7 standard actions and 4 custom actionsEpisodesController
, with 4 standard actions and no custom actionsPodcastEpisodesController
, with 3 standard actions and no custom actionsPodcastCoverImageController
, with 1 standard action and no custom actionsNext up: Treat pivot records as their own resource