Tip 2: Treat properties edited independently as separate resources#2
Tip 2: Treat properties edited independently as separate resources#2adamwathan merged 1 commit intomasterfrom
Conversation
|
@adamwathan The beauty keeps going! Awesome!! |
|
Many times I got caught by questioning myself about where to put these actions. Now I see the light by following your mental process to achieve it. Thank you! |
|
Before this, I had been using the same update method to update just a property of the model by adding a check for the cover image file, for instance: This is trivial if is the only property that needs to be updated in isolation and without a required validation rule. But it gets more complex when you have several fields that can be updated independently and each field has its own validation rules. |
|
This means that we will create a new Controller for each custom action we want? |
|
When you do send put with formRequest from front, you can't retrieve the image. |
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
podcaststable:You might think that what we are doing here is an "update" action against our
podcastsresource, 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
PodcastCoverImageControllerResources 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
POSTrequest toupdate-cover-image, lets make aPUTrequest that treats the cover image like it's own resource:Once we create that new controller and move the old
PodcastsController@updateCoverImageaction 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