I am a newbie in laravel. I have a little problem. I am confused how to convert form input data to db. I want when filling out the form input field it's in the form of a STRING, but I want the db to receive data as an integer. What should I do?
In my blade :
<label ><b>Category</b></label>
<input name="category_id" 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 >{{ $message }}</div>
@enderror
In my controller
$validated = $request->validate([
'title' => 'required|string',
'category_id' => 'required|nullable',
'question_detail' => 'required|string',
]);
Please help
CodePudding user response:
form data is always passed as a string. You need to convert the variable in the backend. Description: https://www.tutorialkart.com/php/php-convert-string-to-int/
CodePudding user response:
Have you tried using the validation 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
You may need to pair this with a numeric form field, on the input, like so: type="number"
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number