Add nullable validation rule
public function rules()
{
return [
'category_id' => 'nullable|required_without:parent_id|integer',
'parent_id' => 'nullable|required_without:category_id|integer',
];
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm using Laravel 7 to create a forum board system, in which a Board model has an inverse ManyToOne relationship to a Category model, and optionally to itself as "parent board".
In my front-end form I have these select elements:
<select name="category_id" id="category_id">
<option value="" selected>Select a Category</option>
@foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name}}</option>
@endforeach
</select>
<select name="parent_id" id="parent_id">
<option value="" selected>Optional Parent Board</option>
@foreach($boards as $board)
<option value="{{ $board->id }}">{{ $board->name}}</option>
@endforeach
</select>
On the backend I'm using a FormRequest to validate the form so that it only requires category_id if parent_id is not present, and vice-versa. This is so that if the user creates/edits a board, and assigns a parent to it, the category_id becomes the same as the parent's; but if it doesn't have a parent, then it must have a category_id.
I'm using the following rules for that:
public function rules()
{
return [
'category_id' => 'required_without:parent_id|integer',
'parent_id' => 'required_without:category_id|integer',
];
}
The problem I'm having right now is that upon form submission, the integer rule triggers if either of the fields are null, and returns the error "The category/parent id must be an integer". The only answers I've found are to enable ConvertEmptyStringsToNul middleware, but it's already active in my app, as I can see the value null (not the string) when dumping the request.
How can I fix this validation?
Add nullable validation rule
public function rules()
{
return [
'category_id' => 'nullable|required_without:parent_id|integer',
'parent_id' => 'nullable|required_without:category_id|integer',
];
}
Please or to participate in this conversation.