One Form Request per Write Action
Reusing one Form Request for store and update looks like less code. The shared rules() has to branch on $this->isMethod('post') to switch between required and sometimes, and the unique check has to ignore a record that exists only on update. Anyone changing a rule first works out which of the two paths the line belongs to.
Don't do this
PHP
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
final class PostRequest extends FormRequest
{
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:255'],
'slug' => [
$this->isMethod('post') ? 'required' : 'sometimes',
'string',
Rule::unique('posts', 'slug')->ignore($this->route('post')),
],
'body' => [
$this->isMethod('post') ? 'required' : 'sometimes',
'string',
],
];
}
}Do this instead
PHP
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
final class StorePostRequest extends FormRequest
{
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:255'],
'slug' => ['required', 'string', Rule::unique('posts', 'slug')],
'body' => ['required', 'string'],
];
}
}PHP
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
final class UpdatePostRequest extends FormRequest
{
public function rules(): array
{
return [
'title' => ['sometimes', 'string', 'max:255'],
'slug' => [
'sometimes',
'string',
Rule::unique('posts', 'slug')->ignore($this->route('post')),
],
'body' => ['sometimes', 'string'],
];
}
}Each request reads top to bottom with no conditionals. The store rules say what a new post needs and the update rules say what a partial edit allows. A rule that applies only to updates, such as refusing a slug change after publishing, goes into UpdatePostRequest and StorePostRequest stays untouched. The cost is that shared rules like max:255 now appear in both files.