LoginSignup
0
1

More than 3 years have passed since last update.

Laravelのマイグレーションファイル名は形式が決まっているようなのでメモ

Posted at

Laravelでcreated_users_table.phpというマイグレーションファイルを作成して、実行したところ、エラーがでた。

database/migrations/create_users_table.php作成
$ php artisan migrate

   Symfony\Component\Debug\Exception\FatalThrowableError  : Class '' not found

    436|     public function resolve($file)
    437|     {
    438|         $class = Str::studly(implode('_', array_slice(explode('_', $file), 4)));
    439|
  > 440|         return new $class;
    441|     }
    442|
    443|     /**
    444|      * Get all of the migration files in a given path.

ああ、マイグレーションファイル名の形式は指定されているみたい。。

正しいファイル名は下記を参考

2019_07_05_052836_create_users_table.php

ついでに、

$class = Str::studly(implode('_', array_slice(explode('_', $file), 4)));

が何をしているかっていうと、

Str::studlyはLaravelのヘルパ関数で、文字列をアッパーキャメルケースに変換。
https://readouble.com/laravel/5.7/ja/helpers.html#method-studly-case

implodeは指定の文字列で連結
explodeは指定の文字列で分割
array_sliceは配列の一部を展開

流れを出力してみると、


$file = "2019_07_05_052836_create_users_table";
$file = explode('_', $file);
var_dump($file);

$file = array_slice($file, 4);
var_dump($file);

$file = implode('_', $file);
var_dump($file);

出力結果
array(7) {
  [0]=>
  string(4) "2019"
  [1]=>
  string(2) "07"
  [2]=>
  string(2) "05"
  [3]=>
  string(6) "052836"
  [4]=>
  string(6) "create"
  [5]=>
  string(5) "users"
  [6]=>
  string(5) "table"
}
array(3) {
  [0]=>
  string(6) "create"
  [1]=>
  string(5) "users"
  [2]=>
  string(5) "table"
}
string(18) "create_users_table"

取得できたcreate_users_tableに対して、Str::studlyでアッパーキャメルケース(CreateUsersTable)に変換して、

return new $class;

インスタンスを生成しているのですなぁ。

これは、自分でも使えそうなので、覚えておく。

0
1
2

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
1