I have a column enabled with datatype bit(1). I am trying to save 0 or 1 value in Database by Laravel eloquent.
$model->enabled = $inputs['enabled'];
$model->save();
I have saved values in my config file.
'enabled' => [
'0' => 'No',
'1' => 'Yes',
],
But when I tried to save these value in database. I was getting error like,
SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column ‘enabled’ at row 1
when i ran query in mysql phpmyadmin, it saved data correctly database.
But running this query by eloquent, it produces error.
5
Answers
So i had solved my question by just adding DB::raw();
like,
Eloquent doesn't work by calling Boolean value directly, first you have to gone through your values in DB::raw();
It works like a charm.
you need tinyint type, in your migration file do
When you migrate with
boolean('column_name')
it creates a column with type tinyint(1) and you can set to model true/1 or false/0 and save. For exampleOr
As per MySQL manual you can use should use
bool
andboolean
which are aliases oftinyint
to store 0 or 1 valueSo use:
https://dev.mysql.com/doc/refman/8.0/en/other-vendor-data-types.html
A boolean in mysql is generaly a tinyint.
Eloquent models can cast boolean automaticaly : https://laravel.com/docs/6.x/eloquent-mutators#attribute-casting
Before saving your model, make sure your variable is a boolean
also you can use mutator to force values.
example : in your model, append :
and in the client code
then method setEnabled is called during assignation and ‘enabled’ will become 1
doc : https://laravel.com/docs/5.8/eloquent-mutators