Home > other >  Laravel migration get connection value from env throws Expression is not allowed as field default va
Laravel migration get connection value from env throws Expression is not allowed as field default va

Time:04-26

I've generated quite lots of migration files. As you know, I've got both development and production databases (even multiple ones).

Inside the migration file, you got the protected $connection definition

<?php 
//...
return new class extends Migration
{
    /**
     * The database connection that should be used by the migration.
     *
     * @var string
     */
    protected $connection = 'dev_conn';

The problem comes when I want to change the connection "dynamically" or more efficiently:

<?php 
//...
return new class extends Migration
{
    /**
     * The database connection that should be used by the migration.
     *
     * @var string
     */
    protected $connection = env('DB_CONNECTION');

But I get the following error.

Expression is not allowed as field default value

Then, it'd be so annoying to change all the files one by one to:

<?php 
//...
return new class extends Migration
{
    /**
     * The database connection that should be used by the migration.
     *
     * @var string
     */
    protected $connection = 'prod_conn';

Then how can I change the connection name in just one line of code, instead of changing every file???

CodePudding user response:

class CustomMigration extends Migration {
  protected $connection = null;

  public function __construct() {
    $this->connection = env('DB_CONNECTION');
  }
}

You cannot set a local property to a function like that in any PHP file, but you should be able to set it in the __construct() method.

You'll just have to make sure any "dynamic" migrations extend this Class instead of the default:

class CreateExampleTable extends CustomMigration {
  // ...
}

You might need to put this CustomMigration class in a different folder, to prevent Laravel trying to run it as a Migration, and apply an appropriate Namespace, but otherwise, this should work.

CodePudding user response:

Multiple database connections are primarily used if you need to use multiple databases on one environment.

Its better to use environment variables to use a different database on development and production

  • Related