Lecture Notes Of Day 6: Laravel Database Migration

 

Lecture Notes Of Day 6

Laravel Database Migration

Objective:

By the end of this class, students will learn how to create and manage database tables in Laravel using migrations. They will be able to apply migrations to set up and modify database schemas for their Laravel applications.

Outcome:

Students will be able to:

1.  Create migration files using php artisan make:migration.

2.  Use Laravel’s Schema Builder to define and manage database tables.

3.  Apply migrations to set up or modify the database structure.

4.  Rollback migrations if needed to revert changes.


1. Introduction to Database Migrations in Laravel

In Laravel, migrations provide a way to define the structure of your database using code. They are like version control for your database schema, allowing you to modify the database schema without having to manually write SQL queries.

Why use Migrations?

  • Consistency: Migrations allow the same database structure to be shared across different environments, making it easier to work with multiple developers.
  • Version Control: Migrations keep track of changes made to the database schema, and you can roll back to a previous state if something goes wrong.
  • Automation: You don’t have to write SQL queries manually for creating or altering tables; Laravel does it for you.

2. Creating Migration Files

To create a new migration, we use the Artisan command-line tool in Laravel. The php artisan make:migration command generates a migration file with a predefined structure.

Creating a Migration:

1.  Command Syntax:

php artisan make:migration create_table_name

Example: To create a migration for a posts table, run:

php artisan make:migration create_posts_table

2.  File Location: After running the command, a new file will be generated in the database/migrations folder. The filename will have a timestamp to ensure the migrations are executed in the correct order. For example:

2024_09_26_123456_create_posts_table.php


3. Migration File Structure

A migration file typically contains two main methods:

  • up(): This method is used to define the changes you want to make to the database (e.g., creating tables, adding columns).
  • down(): This method is used to reverse the changes made in the up() method. It’s essential to define this for rollback functionality.

Example of a Migration File:

<?php 

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

 class CreatePostsTable extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        Schema::create('posts', function (Blueprint $table) {

            $table->id(); // Creates an auto-incrementing primary key 'id' column

            $table->string('title'); // Creates a 'title' column with type VARCHAR

            $table->text('body'); // Creates a 'body' column with type TEXT

            $table->timestamps(); // Creates 'created_at' and 'updated_at' columns

        });

    }

 

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists('posts');

    }

}

  • $table->id(): Automatically creates an auto-incrementing primary key.
  • $table->string('title'): Creates a string column named title.
  • $table->text('body'): Creates a text column for storing long text in the body.
  • $table->timestamps(): Adds created_at and updated_at columns, automatically managed by Laravel.

4. Running Migrations

Once the migration file has been created and the schema defined in the up() method, we need to apply the migration to the database.

1.  Running the Migration: To run all the outstanding migrations, use the following command:

Copy code

php artisan migrate

This will apply the changes defined in all migration files that have not yet been applied to the database.

2.  Database Table Creation: After running the migration, you can check your database (using tools like phpMyAdmin or MySQL Workbench) to see the new posts table that has been created.


5. Rolling Back Migrations

If you need to undo a migration or revert changes, you can use the rollback command. This will call the down() method in your migration files to reverse the changes.

1.  Rolling Back Migrations:

php artisan migrate:rollback

This command rolls back the most recent batch of migrations. You can also roll back multiple batches with the --step option:

php artisan migrate:rollback --step=1

2.  Resetting All Migrations: To undo all migrations and return the database to its original state, use:

php artisan migrate:reset

3.  Refreshing Migrations: If you want to rollback and then re-run all migrations (useful when you're in development and need to rebuild your database), you can use:

php artisan migrate:refresh


6. Schema Builder Methods in Laravel

Laravel provides a Schema Builder that allows you to create and modify database tables. Here are some commonly used methods when defining tables:

  • $table->string('column_name'): Creates a string column (e.g., VARCHAR).
  • $table->integer('column_name'): Creates an integer column.
  • $table->text('column_name'): Creates a text column.
  • $table->boolean('column_name'): Creates a boolean column (TRUE or FALSE).
  • $table->timestamps(): Adds created_at and updated_at columns.

7. Adding Foreign Keys and Relationships

You can also define relationships between tables using foreign keys. For example, if a posts table needs to reference a users table, you can use a foreign key:

$table->unsignedBigInteger('user_id');

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

  • unsignedBigInteger('user_id'): Defines an unsigned integer column for the foreign key.
  • foreign('user_id'): Defines the foreign key relationship.
  • references('id')->on('users'): Specifies that the user_id column in the posts table references the id column in the users table.
  • onDelete('cascade'): Specifies that if a user is deleted, all associated posts should also be deleted.

8. Conclusion

Database migrations are an essential part of Laravel development, allowing you to easily manage your database schema in a version-controlled and automated way. By creating migration files, applying them, and rolling them back when necessary, you ensure that your database structure remains consistent across environments.


Key Points to Remember:

  • Use php artisan make:migration to create migration files.
  • Define database structure in the up() method.
  • Use php artisan migrate to apply migrations.
  • Rollback migrations using php artisan migrate:rollback.
  • Utilize Schema Builder methods to define tables and columns.

Homework/Practice:

1.  Create a migration for a categories table with columns like id, name, description, and timestamps.

2.  Create a migration to add a foreign key relationship between the posts table and users table.



Comments

Popular posts from this blog

MCQs Of Day CRUD 8 Operations with Eloquent

Lecture Notes Of Day 24: Laravel Policies

MCQs of Day 7 Eloquent ORM Basics