我是laravel的新手。我有个小问题。我很困惑如何将表单输入数据转换为数据库。我想填写表单输入字段时,它是在一个字符串的形式,但我希望数据库接收数据作为一个整数。我该怎么办?
In my blade:
<label class="form-label mb-3"><b>Category</b></label>
<input name="category_id" class="form-control @error('category_id') is-invalid @enderror" list="datalistOptions" id="category_id" placeholder="Ketik untuk mencari jenis kategori pertanyaan">
<datalist id="datalistOptions">
@foreach ($categories as $category)
<option value="{{ $category->id }}" {{ old('category_id') == $category->name ? 'selected' : null }}>{{ $category->name }}</option>
@endforeach
</datalist>
@error('category_id')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
In my controller
$validated = $request->validate([
'title' => 'required|string',
'category_id' => 'required|nullable',
'question_detail' => 'required|string',
]);
请帮
表单数据总是作为字符串传递。您需要在后端转换变量。描述:https://www.tutorialkart.com/php/php-convert-string-to-int/
您是否尝试过使用验证numeric
?
$validated = $request->validate([
'title' => 'required|string',
'category_id' => 'required|nullable',
'question_detail' => 'required|string',
'your_number_field' => 'required|numeric'
]);
https://laravel.com/docs/9.x/validation rule-numeric
您可能需要将其与输入上的数字表单字段配对,如:type="number"
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number