Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment specific SSL config in Laravel .env file

I am running Laravel 5.1 and have multiple environments, some that require SSL, and some that don't. When I require SSL, my config in database.php requires the following in the mysql driver:

'options'   => [
    PDO::MYSQL_ATTR_SSL_KEY     => env('MYSQL_SSL_KEY'), // /path/to/key.pem
    PDO::MYSQL_ATTR_SSL_CERT    => env('MYSQL_SSL_CERT'), // /path/to/cert.pem
    PDO::MYSQL_ATTR_SSL_CA      => env('MYSQL_SSL_CA'), // /path/to/ca.pem
    PDO::MYSQL_ATTR_SSL_CIPHER  => env('MYSQL_SSL_CIPHER')
]

The problem is that when I set these env() vars to null in the environments that don't use SSL (e.g local), it breaks (white screen, etc...). I have to either not set the "options" key or set to to an empty array for it to work, which removes the env() vars which then wouldn't work on the SSL environments.

Is there a way to satisfy this key that works for both SSL and non-SSL environments?

like image 995
robarelli Avatar asked Nov 16 '15 17:11

robarelli


1 Answers

You can define a new environment variable that enables or disables SSL usage, then use a ternary operator to load the appropriate configuration.

Add this to your .env file in environments where you need database SSL enabled:

MYSQL_SSL=true // not having this variable defined or being false, will disable SSL

In your config/database.php file, modify the options key value for your connection to be loaded like this:

'options' => (env('MYSQL_SSL')) ? [
    PDO::MYSQL_ATTR_SSL_KEY    => env('MYSQL_SSL_KEY'),  // /path/to/key.pem
    PDO::MYSQL_ATTR_SSL_CERT   => env('MYSQL_SSL_CERT'), // /path/to/cert.pem
    PDO::MYSQL_ATTR_SSL_CA     => env('MYSQL_SSL_CA'),   // /path/to/ca.pem
    PDO::MYSQL_ATTR_SSL_CIPHER => env('MYSQL_SSL_CIPHER')
] : []

I'm usually against using logic in the configuration files, but this is a case where an exception might be made.

like image 113
Bogdan Avatar answered Oct 20 '22 00:10

Bogdan