Урок 02

Создание таблиц

Метод create

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('body');
    $table->timestamps();
});

Всё, что внутри замыкания — определение колонок.

Типы колонок

  • id() — BIGINT AUTO_INCREMENT PRIMARY KEY
  • bigIncrements('id') — то же самое
  • increments('id') — INT AUTO_INCREMENT
  • string('name', 100) — VARCHAR(100)
  • char('code', 4) — CHAR(4)
  • text('body') — TEXT
  • mediumText('body') — MEDIUMTEXT
  • longText('body') — LONGTEXT
  • integer('views') — INT
  • bigInteger('count') — BIGINT
  • smallInteger('age') — SMALLINT
  • tinyInteger('active') — TINYINT
  • boolean('is_active') — BOOLEAN
  • decimal('price', 8, 2) — DECIMAL(8,2)
  • float('rating') — FLOAT
  • double('score') — DOUBLE
  • date('birthday') — DATE
  • time('starts_at') — TIME
  • dateTime('published_at') — DATETIME
  • timestamp('created_at') — TIMESTAMP
  • json('options') — JSON
  • jsonb('meta') — JSONB (PostgreSQL)
  • uuid('uuid') — UUID
  • ulid('ulid') — ULID
  • enum('status', ['draft', 'published']) — ENUM

Специальные колонки

  • timestamps() — created_at и updated_at
  • softDeletes() — deleted_at
  • rememberToken() — для «запомнить меня»
  • foreignId('user_id') — BIGINT для внешнего ключа

Проверка существования

if (Schema::hasTable('posts')) {
    //
}

if (Schema::hasColumn('posts', 'title')) {
    //
}

Удаление

Schema::drop('posts');
Schema::dropIfExists('posts');
Schema::dropColumns('posts', ['title', 'body']);

Переименование

Schema::rename('posts', 'articles');