2

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)
Gustavo Bissolli
  • 1,551
  • 3
  • 22
  • 36

2 Answers2

5

FormData 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

Kowsalya
  • 1,378
  • 16
  • 25
2

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;
    }
}