I am using form requests in Laravel for validation. I have noticed a pattern that emerges all the time and I couldn't find a solution for it on SE (or at least googling it didn't help me).
Let's say we are creating an API and we are using Laravel's apiResource to create the usual CRUD methods: store
, update
and delete
Obviously, when we are storing a new record, the field id
is not required, but the rest of the fields might be required (and in most cases are). But when we are updating a record, we face the opposite situation. id
is required while other fields are no longer required.
Is it possible to handle this situation with one form request in Laravel? Can we use Laravel's required_if
in an intelligent way to avoid code duplication?
Edit: it doesn't have to be necessarily a Laravel solution. A solution that uses PHP would be fine too (as long as it is clean and follows SOLID principles).
My Answer:
One way to handle this situation in Laravel is to create a custom validation rule that checks the request method and determines which fields are required based on that. Here's an example of how you can achieve this:
1. Create a new custom validation rule by running the following command in your terminal:
bash
php artisan make:rule RequiredFields
2. Open the `RequiredFields` rule class that was generated in the `app/Rules` directory and implement the `passes` method like this:
php
public function passes($attribute, $value)
{
$method = request()->getMethod();
if ($method === 'POST') {
return !empty(request($attribute));
} elseif ($method === 'PUT' || $method === 'PATCH') {
return !empty(request($attribute)) && request($attribute) != null;
}
return true;
}
3. In your form request class, you can now use the `RequiredFields` rule for your validation like this:
php
public function rules()
{
return [
'id' => ['required', new RequiredFields],
'name' => ['required', new RequiredFields],
'email' => ['required', 'email', new RequiredFields],
// Add other fields as needed
];
}
With this setup, the `RequiredFields` rule will check the request method and determine which fields are required based on that. This way, you can avoid code duplication and keep your form request clean and following SOLID principles.
Rate this post
5 of 5 based on 1585 votesComments