Laravel PDO Connection Options
PHP's PDO has many attribute options you can configure. Occasionally, we may need to change some options to fit our infrastructure or code needs. For example, we might need to turn on persistent connections.
Sidenote: Consider carefully if you really want to turn on persistent connections.
I was curious about whether Laravel used persistent connections by default, as CodeIgniter does (turns out Laravel does not). In my search, I also discovered that we can indeed pass configuration options to our PDO object.
If we check out the Illuminate\Database\Connectors\Connector.php file, we can see that there are some default attributes:
/**
* The default PDO connection options.
*
* @var array
*/
protected $options = array(
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
PDO::ATTR_STRINGIFY_FETCHES => false,
PDO::ATTR_EMULATE_PREPARES => false,
);
In the same file, we can also see a method getOptions
, which pull options out of our configuration.
/**
* Get the PDO options based on the configuration.
*
* @param array $config
* @return array
*/
public function getOptions(array $config)
{
$options = array_get($config, 'options', array());
return array_diff_key($this->options, $options) + $options;
}
This is good news, because it means we can pass in our own options into the configuration! This is seen in the createConnection()
method - the $options
array is passed to the PDO object upon creation of the connection:
/**
* Create a new PDO connection.
*
* @param string $dsn
* @param array $config
* @param array $options
* @return PDO
*/
public function createConnection($dsn, array $config, array $options)
{
$username = array_get($config, 'username');
$password = array_get($config, 'password');
return new PDO($dsn, $username, $password, $options);
}
So, how do we pass in PDO attribute settings of our own? We can go back to our configuration file!
Head to your database configuration file, likely app/config/database.php
. Here we can add an 'options' portion to our connection. I'll edit the mysql
connection in this example:
<?php
return array(
/* other settings removed for brevity */
'connections' => array(
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'options' => array(
PDO::ATTR_PERSISTENT => true,
),
),
/* other connections removed for brevity */
)
)
Note that in the above example, we added in the options
array and used one of PDO's attributes in order to turn on persistent connections.
There we have it, we can configure PDO in any way we need!
If you're curious, you can see how the MySqlConnector class, which extends
Connector
, takes the configuration and applies it to the connection.