laravel
  1. laravel-migration-structure

Migration Structure - Laravel Migration

Laravel Migration is a feature of the Laravel framework that allows you to define and maintain database schema in a version-controlled manner. In this article, we'll take a closer look at the migration structure in Laravel.

Migration Structure

A migration in Laravel is a PHP file that has a class with two methods: up() and down(). The up() method defines the changes that should be made to the database schema, while the down() method defines how to revert those changes. When you run a migration, Laravel executes the up() method, and when you roll back a migration, Laravel executes the down() method.

Syntax

php artisan make:migration CreateUsersTable --create=users

Example

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Output

When you run this migration, it will create a users table in your database with the specified columns. When you roll back this migration, it will drop the users table.

Explanation

In this example, the up() method creates a users table with the specified columns using the Schema::create() method. The down() method drops the users table using the Schema::dropIfExists() method.

Use

Migrations can be used to define and maintain database schema in a version-controlled manner. They allow for easy database schema changes and can be rolled back in case of errors.

Important Points

  • Migration files should have a descriptive name that describes the changes made.
  • The up() method should define the changes that should be made to the database schema.
  • The down() method should define how to revert those changes.
  • Migrations can be used to create and modify tables, add and remove columns, and perform other database schema changes in a version-controlled and repeatable way.

Summary

In this article, we looked at the migration structure in Laravel. We covered the syntax and example of creating a migration, explained the output and explanation of the up() and down() methods, and discussed the uses and important points of migrations. In summary, migrations are a powerful tool for defining and maintaining database schema in a version-controlled and repeatable way.

Published on: