0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravel 12 で Schema::setConnection() は使えなくなりました

Last updated at Posted at 2025-03-06

Schema::setConnection() とは

Laravel 11.31 で、config で設定したデータベース以外でも簡単に使える、dynamic builder が追加されました(参照 Dynamic Cache, Database, and Mail Builders in Laravel 11.31 - Laravel News)。

$db = DB::build([
    'driver' => 'sqlite',
    'database' => データベースファイルへのパス,
    'prefix' => '',
    'foreign_key_constraints' => true,
]);

これを利用して、新しいテーブルを作成したい場合などは例えば次のようなコードが書けました。

$schema = Schema::setConnection($db); // <-----ここで setConnection() 使う

if (!$schema->hasTable('table_hoge')) {
    $schema->create("table_hoge", function ($table) {
      $table->string('hoge_id');
      $table->json('hoge_meta');
      :
      :
});

しかし、Laravel 12 ではこの setConnection() メソッドは削除されましたので、上記コードはエラーとなります。

Laravel 12 では 11 からの破壊的変更はほぼないと謳われていますが、「全くない」といっているわけではないので注意が必要ということです。

修正方法

次のように修正します。

$schema = $db->getSchemaBuilder(); // <-----ここで setConnection() 使っていたのを修正

if (!$schema->hasTable('table_hoge')) {
    $schema->create("table_hoge", function ($table) {
      $table->string('hoge_id');
      $table->json('hoge_meta');
      :
      :
});

簡単ですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?