JSON代表bit / boolean字段显示字符串类型

{
  "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

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.

Maybe you can use if() function, so

Select RoleID, Role, if(IsPredefined=1,'true','false') as IsPredefined form tblrole;

If you are using Eloquent model you can use Accessors and Mutators so add accessor method in your eloquent model.

public function getIspredefinedAttribute($value)
{
    return ($value==1)?true:false;
}