phayes0289's avatar

Converting a "1" or "0" Request Value So It Can Be Saved As a BIT in MySQL

I have a select input that has two options.... yes and no. The value passed to the controller is a "0" (zero) or a "1". I am trying to save it to a boolean field in MySQL. Here is the update method I am using:

public function update(Request $request, PibsFeature $pibsFeature)

        {
            $formFields = $request->validate([
                'pibs_id' => ['required'],
                'title' => ['required', 'min:3'],
                'type' => ['required', 'min:3'],
                'tags' => ['nullable'],
                'description' => ['required'],
                'image' => ['nullable'],
                'enable_map' => ['required']
            ]);

            $pibsFeature->update($formFields);

            $pibsFeature->save();

            $pibs = pibs::find($request->pibs_id);

            return redirect()->route('pibs.features.index',compact('pibs'))->with('message', 'Your collection has been created saved!');
        }

When the data gets submitted, it causes the following SQL error, which I assume is from converting the 1 or 0 into a binary value?:

SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'enable_map' at row 1

How do I convert the value so it can be stored in MySQL as a "bit" field.... or should I do something else altogether?

TIA

0 likes
9 replies
newbie360's avatar

@phayes0289 I always use unsignedTinyInteger() for bool type, it is really hard to query bit type

or you can use $table->boolean('confirmed'); it is equal TINYINT(1)

newbie360's avatar

@phayes0289 in MySQL bit column type, you can't store 0 | 1

it use somethings like this instead b'0'

sorry i'm not understand about bit column type =(

Sinnbeck's avatar

Just add a cast on the model

protected $casts = [
    'enable_map' => 'boolean' 
];
Sinnbeck's avatar

And no need to save twice. Update already saves

Please or to participate in this conversation.