Search code examples
phplaravel-5laravel-5.1laravel-5.3

JSON shows string type in behalf of bit/boolean field


{
  "Status": true,
  "Message": "Roles retrieved successfully",
  "Data": [
    {
      "RoleID": 1,
      "Role": "Super Admin",
      "IsPredefined": "1",
      "IsActive"    : "1",
    }
  ]
}

I am fetching above results in json format. I am using below query to fetch the data from MySql database.

I am using Model and my code is: RoleModel::all()

I am using PHP-Laravel 5.3

Is there any way to make the resultset like below.

{
  "Status": true,
  "Message": "Roles retrieved successfully",
  "Data": [
    {
      "RoleID": 1,
      "Role": "Super Admin",
      "IsPredefined": true,
      "IsActive"    : true,
    }
  ]
}

Issue is in IsPredefined. I want to retrieve it Boolean type. In database it is of type bit


Solution

  • Attribute Casting

    My model was like below

    class RoleModel extends Model {
    
        public $table = 'tblrole';
        public $primaryKey = 'RoleID';
        public $timestamps = true;
    
    }
    

    It should be like below.

    class RoleModel extends Model {
    
        public $table = 'tblrole';
        public $primaryKey = 'RoleID';
        public $timestamps = true;
    
        protected $casts = [
            'IsPredefined'  => 'boolean'
        ];
     }
    

    Moreover, Database table must have datatype = 'BIT' for boolean values so that it may occupy only 0 or 1 values.