I do something like that occasionally, however I create a create and update method within the FormRequest. The rules() method just detects the HTTP verb and delegates to the appropriate create/update method, which returns the appropriate rules array for that request. I just think it's easier at a quick glance to see what's going on without having to do ternary operations in your head, and it's very clear what the rules are for each case.
Aug 7, 2019
4
Level 13
Store and update request are the same except the unique id. A way to merge?
Hi all, I'm creating my first full project(blog).
With the obsession to write DRY code, I created a CategoryStoreUpdateRequest (and not a StoreRequest + a UpdateRequest) to control the rules to pass and messages to return when store or update route is needed.
I'm using this personnal trick to do this:
public function rules()
{
$name_rules = ($this->method() == 'PATCH') // else == 'POST'
? 'required|string|max:50|unique:categories,name,'.$this->category->id
: 'required|string|max:50|unique:categories,name';
return [
'name' => $name_rules,
'parent_id' => 'nullable'
];
}
I just want to know if some of you is seeing an issue to do this that way??
Please or to participate in this conversation.