Laravel PDO Settings?
I know this is an old thread, but I found a global solution to this issue for MSSQL drivers and PHP 7 (single change that affects all tables / models). Hopefully this will help others that are struggling with the same.
- Get the latest version of the drivers from the Git Repository (Microsoft/msphpsql). The current version released on the Microsoft Downloads page is an older version and won't work (as of 9/13/2016).
- Copy the appropriate DLLs into your
php/ext
folder (replacing/deleting the older version). You'll probably need to stop/start your web server (definitely, if IIS) to free the original files up for replacement/deletion. If the filenames changed from the previous version you had installed, update yourphp.ini
file. Update the driver configuration to include the new
PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE
parameter:'sqlsrv' => [ 'driver' => 'sqlsrv', 'host' => env('DB_HOST', 'localhost'), 'database' => env('DB_DATABASE', 'database'), 'username' => env('DB_USERNAME', 'laravel'), 'password' => env('DB_PASSWORD', 'password#1'), 'charset' => 'utf8', 'prefix' => '', 'options' => array( PDO::ATTR_STRINGIFY_FETCHES => false, PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE => true ), ],
For explanation of the solution, I found it by working my way through the source code on the Git Repository. Of course it would have been a lot easier if I had read the Announcements section of the README file first:
July 28, 2016 (4.1.0): Thanks to the community's input, this release expands drivers functionalities and also includes some bug fixes:
SQLSRV_ATTR_FETCHES_NUMERIC_TYPE
connection attribute flag is added to PDO_SQLSRV driver to handle numeric fetches from columns with numeric Sql types (only bit, integer, smallint, tinyint, float and real). This flag can be turned on by setting its value inPDO::setAttribute
totrue
, For example,$conn->setAttribute(PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE,true);
IfSQLSRV_ATTR_FETCHES_NUMERIC_TYPE
is set totrue
the results from an integer column will be represented as anint
, likewise, Sql types float and real will be represented asfloat
. Note for exceptions:
- When connection option flag
ATTR_STRINGIFY_FETCHES
is on, even whenSQLSRV_ATTR_FETCHES_NUMERIC_TYPE
is on, the return value will still be string.- When the returned PDO type in bind column is
PDO_PARAM_INT
, the return value from a integer column will be int even ifSQLSRV_ATTR_FETCHES_NUMERIC_TYPE
is off.
I believe this issue is related to the PDO driver used (thats installed with PHP, not laravel configuration).
Not quite what you're looking for but could potentially solve your problems. Since laravel 5 theres been a casts feature on eloquent where your columns are automatically cast to your pre-defined types. See http://laravel.com/docs/5.0/eloquent#attribute-casting
// Eloquent Model
protected $casts = [
'int_column' => 'int',
];
Your int_column
would then automatically be cast to an int when the model is retrieved from the database