I am trying to submit a FormData javascript Object trough the Axios library and I can't make it work because there a boolean field (is_active) who must go to my api as boolean and the FormData object is converting it to string!
I have tried to make it without FormData and then it goes perfectly!
Any body knows the best way to make it work? Actually I've made a really bad job on my Laravel Request to fix the field... I don't think it's the best idea but it works for now!
Anybody has a good solution for it?
There is my current working code but I would like to make it better!
My controller and my request:
PS: I have made that IF on the $rules function to fixes the boolean issue... If I let it go as string I would have problem with my database where the field must be boolean and I also had to remove my boolean validate on that field
class PostRequest extends FormRequest
{
public function rules()
{
if (in_array($this->get('active'), ['true', 'false'])) {
$this->offsetSet('active', $this->get('active') == 'true');
}
$rules = [
'title' => 'required|string',
'slug' => 'required|alpha_dash|unique:posts,slug',
'photo' => 'required|image',
'publish_date' => 'required|date_format:d/m/Y',
'summary' => 'required',
'content' => 'required',
'author_id' => 'required|exists:authors,id',
'category_id' => 'required|exists:categories,id,flag,posts',
// 'active' => 'boolean',
];
return $rules;
}
}
class PostsController {
public function store(PostRequest $request)
{
try {
$model = new Post($request->all());
$model = $model->save();
} catch (\Exception $e) {
return response()->json($e->getMessage(), 422);
}
return $model;
}
}
There is now my javascript code
PS: I am working with services so my createPost trigger my axios client who makes the request
let data = new FormData()
let record = _.cloneDeep(this.record)
for (var key in record) {
if (record[key] === 'true' || record[key] === 'false')
data.append(key, record[key] === 'true')
else
data.append(key, record[key])
}
return _.isNil(this.record.id) ? createPost(data) : updatePost(data.id, data)
I am trying to submit a FormData javascript Object trough the Axios library and I can't make it work because there a boolean field (is_active) who must go to my api as boolean and the FormData object is converting it to string!
I have tried to make it without FormData and then it goes perfectly!
Any body knows the best way to make it work? Actually I've made a really bad job on my Laravel Request to fix the field... I don't think it's the best idea but it works for now!
Anybody has a good solution for it?
There is my current working code but I would like to make it better!
My controller and my request:
PS: I have made that IF on the $rules function to fixes the boolean issue... If I let it go as string I would have problem with my database where the field must be boolean and I also had to remove my boolean validate on that field
class PostRequest extends FormRequest
{
public function rules()
{
if (in_array($this->get('active'), ['true', 'false'])) {
$this->offsetSet('active', $this->get('active') == 'true');
}
$rules = [
'title' => 'required|string',
'slug' => 'required|alpha_dash|unique:posts,slug',
'photo' => 'required|image',
'publish_date' => 'required|date_format:d/m/Y',
'summary' => 'required',
'content' => 'required',
'author_id' => 'required|exists:authors,id',
'category_id' => 'required|exists:categories,id,flag,posts',
// 'active' => 'boolean',
];
return $rules;
}
}
class PostsController {
public function store(PostRequest $request)
{
try {
$model = new Post($request->all());
$model = $model->save();
} catch (\Exception $e) {
return response()->json($e->getMessage(), 422);
}
return $model;
}
}
There is now my javascript code
PS: I am working with services so my createPost trigger my axios client who makes the request
let data = new FormData()
let record = _.cloneDeep(this.record)
for (var key in record) {
if (record[key] === 'true' || record[key] === 'false')
data.append(key, record[key] === 'true')
else
data.append(key, record[key])
}
return _.isNil(this.record.id) ? createPost(data) : updatePost(data.id, data)
Share
Improve this question
asked Oct 15, 2016 at 22:09
Gustavo BissolliGustavo Bissolli
1,5713 gold badges23 silver badges36 bronze badges
3 Answers
Reset to default 5FormData can only be sent in the format of string or buffer, so you cant send boolean through FormData. If you would really need only boolean, just convert the string to boolean on server-side.
To convert string to boolean in php
$boolValue = ($stringToTest === 'true');
reference from this stackoverflow answer for the above code
In your frontend formData you can send 1
or 0
instead of true
or false,
and Laravel can recognize them as boolean
as long as you set your validation rules for them.
class PostRequest extends FormRequest
{
public function rules()
{
$this->validate([
'active' => [
'required',
'boolean'
]
);
// Now you can check it like this
if ((bool) $this->active) {
// is true
} else {
// is false
}
// Your other rules
$rules = [
];
return $rules;
}
}
I solved this problem in Laravel 10 app using trait:
<?php
namespace App\Traits;
trait FormRequestCastJsFormData
{
/**
* @param array<string, string> $data
* @param string[] $boolKeys
* @param string[] $nullKeys
*/
private function castFormData(array $data, array $boolKeys = [], array $nullKeys = []): array
{
foreach ($data as $key => $value) {
if (in_array($key, $nullKeys, true) && $value === 'null') {
$data[$key] = null;
} elseif (in_array($key, $boolKeys, true)) {
$data[$key] = filter_var($value, FILTER_VALIDATE_BOOLEAN);
}
}
return $data;
}
}
This trait is used in my UpdateRequest in the prepareForValidation()
method. Here is an example:
class UpdateRequest extends FormRequest
{
use FormRequestCastJsFormData;
public function rules(): array
{
return [
// ...
'published' => 'required|boolean',
'cover' => 'nullable|image',
];
}
protected function prepareForValidation(): void
{
$this->merge(
$this->castFormData(
$this->all(),
boolKeys: ['published'],
nullKeys: ['cover'],
),
);
}
}