Langsung ke konten utama

Laravel migration for beginner, create table, add, alter and drop column


Laravel migration is a powerful tool that allows you to manage your database schema through code. It's a way to version control your database structure and automate changes to your schema.

In this article, we'll go through the basics of Laravel migration and show you how to use it in your Laravel projects.

What is Laravel Migration?

Laravel migration is a database schema version control system. It allows you to manage your database schema through code instead of manually running SQL scripts. With Laravel migration, you can define your database schema using PHP code and Laravel will handle the rest.

Migration files are stored in the database/migrations directory of your Laravel project. Each migration file contains a class that extends the Illuminate\Database\Migrations\Migration class. This class provides methods for creating, modifying, and deleting database tables, columns, and indexes.

Why Use Laravel Migration?

Laravel migration offers a number of benefits over manually managing your database schema. Here are a few reasons why you should use Laravel migration:

Version Control: Laravel migration allows you to version control your database schema just like you version control your code. This means you can easily roll back changes or migrate your database to a specific version.

Consistency: By defining your database schema in code, you can ensure that your database structure is consistent across all environments. This can prevent issues that arise from different versions of the schema in different environments.

Automation: Laravel migration allows you to automate the process of modifying your database schema. This can save you time and reduce the risk of errors when making changes to your schema.

Creating a Migration

To create a migration in Laravel, you can use the make:migration Artisan command. This command generates a new migration file in the database/migrations directory with a timestamp and a descriptive name.

Here's an example of how to create a migration to create a new users table:

php artisan make:migration create_users_table --create=users

This command generates a new migration file named something like 2023_03_11_000000_create_users_table.php. The --create=users option tells Laravel to generate a migration for creating a new users table.

The generated migration file will contain a up method and a down method. The up method is used to define the changes that will be made to the database schema, and the down method is used to define how to undo those changes.

Here's an example of how to define the up method to create a new users table:

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();
    });
}

This code creates a new users table with columns for name, email, email_verified_at, password, remember_token, and timestamps.

Running Migrations

To run your migrations, you can use the migrate Artisan command. This command will execute all of the pending migrations.

php artisan migrate

 You can also use the migrate:rollback command to roll back the last batch of migrations:

php artisan migrate:rollback

This command will undo the last batch of migrations.

Migration to add new column

For example we need to add 3 column in users table first_name, middle_name, and last_name to an existing table using Laravel migration, you can follow these steps:

Step 1: Generate a new migration file

php artisan make:migration add_name_fields_to_users_table --table=users

This command will create a new migration file in the database/migrations directory with a name like 2023_03_11_000000_add_name_fields_to_users_table.php. The --table=users option tells Laravel to add the new columns to the users table.

Step 2: Define the up method to add the columns

This code adds three new columns to the users table: first_name, middle_name, and last_name. Note that we've specified the nullable() method for the middle_name column to indicate that it can be empty.

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('first_name');
        $table->string('middle_name')->nullable();
        $table->string('last_name');
    });
}

Step 3: Define the down method to remove the columns 

public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('first_name');
        $table->dropColumn('middle_name');
        $table->dropColumn('last_name');
    });
}

This code removes the three columns from the users table if we need to roll back the migration.

Step 4: Run the migration

php artisan migrate

This command will apply the changes to the database schema and add the new columns to the users table.

And that's it! You have successfully added columns for first_name, middle_name, and last_name to the users table using Laravel migration.

How to drop column using migration

For example we need to drop middle_name column using migration. To drop the middle_name column from the users table using Laravel migration, you can follow these steps:

Step 1: Generate a new migration file

php artisan make:migration remove_middle_name_from_users_table --table=users

This command will create a new migration file in the database/migrations directory with a name like 2023_03_11_000000_remove_middle_name_from_users_table.php. The --table=users option tells Laravel to modify the users table.

Step 2: Define the up method to drop the column

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('middle_name');
    });
}

This code drops the middle_name column from the users table.

Step 3: Define the down method to add the column back 

public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('middle_name')->nullable();
    });
}

This code adds the middle_name column back to the users table if we need to roll back the migration.

Step 4: Run the migration

php artisan migrate

This command will apply the changes to the database schema and drop the middle_name column from the users table.

And that's it! You have successfully dropped the middle_name column from the users table using Laravel migration. 

Change column name using migration

For example we need to change the fist_name column name into full_name. To change the first_name column to full_name in the users table using Laravel migration, you can follow these steps:

Step 1: Generate a new migration file

php artisan make:migration rename_first_name_to_full_name_in_users_table --table=users

This command will create a new migration file in the database/migrations directory with a name like 2023_03_11_000000_rename_first_name_to_full_name_in_users_table.php. The --table=users option tells Laravel to modify the users table.

Step 2: Define the up method to rename the column

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->renameColumn('first_name', 'full_name');
    });
}

This code renames the first_name column to full_name in the users table.

Step 3: Define the down method to rename the column back 

public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->renameColumn('full_name', 'first_name');
    });
}

This code renames the full_name column back to first_name in the users table if we need to roll back the migration.

Step 4: Run the migration

php artisan migrate

This command will apply the changes to the database schema and rename the first_name column to full_name in the users table.

And that's it! You have successfully changed the first_name column to full_name in the users table using Laravel migration. 

Komentar

Postingan populer dari blog ini

Fungsi lain tombol penerima panggilan di headset

Kegunaan tombol yang berada di headset utamanya adalah untuk menerima panggilan dan pause panggilan. Dan headset itu sendiri, kadang juga digunakan untuk mendengarkan music, digunakan bersama saat main game, supaya suara yang dikeluarkan oleh gadget tidak terlalu keras sehingga mengurangi beban gadget. Dengan mengurangi beban gadget, ada beberapa yang beranggapan kalau itu akan menghemat batere.

Apa itu index file seperti index.html, index.php kegunaannya dan bagaimana membuat custom nya

Index file adalah file yang berfungsi sebagai halaman utama atau tampilan pertama dari sebuah website. File ini memiliki nama default yang bervariasi, tergantung pada jenis server dan konfigurasinya, namun beberapa nama default yang umum digunakan adalah index.html, index.php, index.jsp, atau index.asp.

Membersihkan cache dan dalvik-cache menggunakan link2sd

Mungkin banyak yang menanyakan kenapa internalnya selalu berkurang free space nya. Padahal tidak menginstall applikasi baru. Hanya melakukan aktifitas normal. Dan sampai pada waktunya, internal memory low dan tidak bisa menambah aplikasi baru lagi.  Ada kemungkinan file cache dari sebuah aplikasi atau dalvik yang dibuat oleh OS android sudah  mulai membengkak. Sehingga perlu di bersihkan secara manual supaya tersedia penyimpanan kosong yang banyak. Sebelum mengetahui cara membersihkan cache dan dalvik cache, kita kupas sekilas apa itu cache dan dalvik cache. Cache adalah sebuah data file sementara yang di hasilkan oleh sebuah applikasi guna mempercepat pemrosesan dimasa yang akan datang (Cache Wikipedia) .  Dalvik-cache adalah ruang kosong sementara yang di pake oleh java virtual machine untuk menjalankan aplikasi android (Dalvik Wikipedia) .