1

I want to create several schemas to my database using migration. I have this code:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateSchemaAdministracion extends Migration
{
    public function up()
    {
        DB::unprepared("CREATE SCHEMA `administracion`");
    }

    public function down()
    {
        DB::unprepared('DROP SCHEMA `administracion`');
    }
}

I tried this way but I got: Invalid schema name: 7 ERROR: No schema has been selected.

3
  • Try something like DB::getConnection()->statement('CREATE DATABASE :schema', ['schema' => 'administracion']); maybe?
    – miken32
    Commented Sep 21, 2018 at 19:05
  • 3
    I don't think that it's a responsibility of a migration to create databases. Commented Sep 21, 2018 at 20:27
  • 1
    It'd also be faulty to assume the db user has privileges to create their own database. Commented Sep 21, 2018 at 20:31

2 Answers 2

2

Try using DB::statement with DB::raw.

I tested this with Laravel 5.8. I guess it should work with earlier versions too.

\DB::statement(\DB::raw("CREATE SCHEMA administracion"));

You can then use it with the schema as prefix. Like this:

Schema::create('administracion.mytable', function (Blueprint $table) {
    $table->bigIncrements('id');
    ...
});

Notice for rollback operation: consider that in postgres you cannot drop a schema if it has elements. You should remove them before removing the schema.

-1
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAdministracionTable extends Migration
{

  public function up()
  {
    Schema::create('administracion', function (Blueprint $table) {
      $table->increments('id');
      $table->string('name');
      $table->string('airline');
      $table->timestamps();
    });
  }


  public function down()
  {
    Schema::drop('administracion');
  }
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.