How to get Laravel Query Builder result as integer

ぐ巨炮叔叔 提交于 2019-12-03 08:07:19

Casting is not a solution but a workaround to the problem. Your actual problem is missing mysqlnd plugin.

Check whether mysqlnd is installed like so

$ sudo dpkg -l | grep 'mysqlnd'

If it's not installed, you need to install it like so (assuming you have php5)

$ sudo apt-get install php5-mysqlnd

These commands are for ubuntu. If you have something else, just convert them to your appropriate OS.

When fetching by select it populates the $attribute internal property with raw data returned by the underlying driver, so generally the MySQL driver is configured to return all columns as strings. Here it does not casts the id attribute to integer.

You have to manually cast it to integer. you can either use (int) $variable syntax to cast it to integer on the fly where you are accessing the attribute of the model or you can make a mutator for that reason.

public function getIdAttribute($value)
{
    return (int) $value;
}

Or you can cast your attribute

protected $casts = [
    'id' => 'integer',
];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!