Saturday, December 29, 2018

php - Sending Boolean with FormData Javascript - Vuejs + Laravel app

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)

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...