Laravel, Migration Schema Class

Hy, I have a question about creating a table (usually working with a database) in laravel through migrations.

I have something like this (from happy code)

<?php Schema::create('users', function($table) { $table->increments('id'); $table->string('username', 32); $table->string('email', 320); $table->string('password', 64); $table->integer('role'); $table->boolean('active'); $table->timestamps(); }); 

OK, this will create user tables with 9 fields, but I get embarrassed by this callback. First of all, the variable "$ table" is an instance of which class? Can someone explain to me what happened here, respectively, how it works?

+4
source share
1 answer

Well, here's how it goes:

  • When you call Schema::create() , it creates a Blueprint object associated with the name of the table that you passed as an argument.
  • The second parameter, the callback, is Closure , which receives this previously created Blueprint object as an argument to $table and acts on it.
  • When you call methods on the $table object, it actually connects it to the Grammar class, according to your database. That is, if you use a MySQL database, it will use the MySqlGrammar class. This ensures that you get valid SQL for any database you use without worrying about it.
  • Finally, he executes all the commands and does all the work for you.

If you want to view the generated SQL queries, you can add the --pretend option to the migrate command. I would recommend saving it to a file so you can read it easily. Example:

 php artisan migrate --pretend > app/storage/migration.sql 

This will save it in the app/storage/migration.sql file.

+9
source

Source: https://habr.com/ru/post/1486926/


All Articles