Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel, migrations Schema class

Hy, i have question about creating table(generally working with DB) in laravel through migrations.

I have something like this(from code happy)

    <?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 table "users" with 9 fields, but I'm getting confused by this callback. First of all variable "$table" is instance of which class? Can someone explain me what happened here, respectively how this works?

like image 563
Srle Avatar asked Dec 27 '22 01:12

Srle


1 Answers

Well, here's how it happens:

  1. When you call Schema::create(), it creates a Blueprint object, linked to the table's name you passed as argument.
  2. The second parameter, the callback, is a Closure that will receive this previously created Blueprint object as the $table argument, and act on it.
  3. When you call methods on the $table object, it is actually wiring it to a Grammar class, according to your database. That is, if you are using a MySQL database, it will use MySqlGrammar class. This ensures you get valid SQL for any database you use, without having to worry about it.
  4. Finally, it executes all the commands, and does all the job for you.

If you wish to see the actual SQL queries generated, you can add the --pretend option to the migrate command. I'd recommend saving it in a file, so you can read it more easily. Ex:

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

This would save it in app/storage/migration.sql file.

like image 159
rmobis Avatar answered Jan 08 '23 03:01

rmobis