1

I receive data from a API request and it contains a value "true" or "false".

Before I've used PDO::PARAM_BOOL to bind the value and insert it into MySQL

Now I'm using Laravel and I want to know how I can insert this value as boolean value 1 or 0.

I've created a migration which contains

$table->boolean('businessorder');  

I save the data in an array and insert it in my table:

$orderarray = [];

  foreach($csv as $data => $orderdata){
    $orderarray[] = [
    ...
    'businessorder' => $orderdata['is-business-order'],
    ...
    ];

  }

I receive the following error

SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'false' for column 1  

The error message also shows the data to insert in the database as "false" not as 0.

How can I make sure it will insert 0 or 1 instead of true or false

When I do

'businessorder' => (bool)$orderdata['is-business-order'],  

It will set everything to 1 (because (bool)'false' is true)

hayashir
  • 33
  • 1
  • 6

2 Answers2

1

When you try to put the value of $orderdata['is-business-order'] into the DB column, MySQL tries to put true or false.

But true or false cannot be stored in a boolean type column. So we can do something like the below code to get 1 or 0 instead of true or false.

businessorder' => ($orderdata['is-business-order']=='true'?1:0)
jpsmith
  • 11,023
  • 5
  • 15
  • 36
0

According to this post you could do something like this:

'businessorder' => filter_var($orderdata['is-business-order'], FILTER_VALIDATE_BOOLEAN),
Marco Cazzaro
  • 661
  • 8
  • 13