Naturally when you customise the Request it can only serve one purpose. That is to validate a series of rules and
return specified error messages, on data held in the $request
object.
I feel there is no point in demonstrating a generic code example not when you have already most likely have experience in the customization, anyway.
To save me some time I use a switch
inside the rules
class method. You switch either on one set of rules or the other based on the request being POST or PUT.
Here is an example.
public function rules(Request $request)
{
switch ($this->method()) {
case 'POST':
return [
'title'=>
[
'required'
, 'string'
]
, 'topic'=>
[
'required'
, 'string'
]
, // etc...
];
break;
case 'PUT':
return [
'title' =>
[
'required'
, 'string'
]
, 'topic' =>
[
'required'
, 'string'
]
, 'id' =>
[
'required'
, 'string'
]
, // etc...
];
break;
}
}
public function messages()
{
switch ($this->method()) {
case 'POST':
return [
'title.required' => 'Enter a post title'
, 'topic.required' => 'Enter a post topic'
, // etc...
];
break;
case 'PUT':
return [
'title.required' => 'Enter a post title'
, 'topic.required' => 'Enter a post topic'
, 'id.required' => 'Primary key missing'
, // etc...
];
break;
}
The POST is the when you create a new row of data, and the PUT (or PATCH if you prefer) for when you have a record to update.
That's all there is to it really, you have dual purpose increasing your productivity too.
Content on this site is licensed under a Creative Commons Attribution 4.0 International License. You are encouraged to link to, and share but with attribution.
Copyright ©2024 Leslie Quinn.