Search⌘ K
AI Features

Comprehensive Guide to Laravel Migrations Setup and Implementation

Explore the process of setting up and implementing database migrations in Laravel. Understand how to configure your database environment, create and modify tables, manage migrations with Artisan commands, and safely roll back changes to maintain database integrity.

Introduction to database setup in phpMyAdmin

Laravel supports multiple database management system (DBMS) connections. phpMyAdmin is a popular web-based administration tool used for managing and administering MySQL or MariaDB databases. It comes with a built-in installation of MySQL libraries. Both CLI and phpMyAdmin can opt to create a database.

Preview of phpMyAdmin
Preview of phpMyAdmin

Overview of Laravel environment variables setup

In the Laravel framework, configuration settings are saved using environment variables in the .env file. These settings can change depending on where the application is being hosted. This allows developers to store sensitive information (such as email passwords), host database credentials, and other required configuration options. These configurations can be reused without writing them into our code. Laravel provides an .env file in the root directory. This file uses a format with KEY=VALUE syntax to assign values to global configuration-based variables. Here’s an example of a basic .env file:

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
............................
Preview of a Laravel .env file

After creating the database, the next step is to set up database configuration variables in the Laravel app. Laravel provides six environment variables to manage database-related configuration. The variables, along with their definitions, are given below:

  • DB_CONNECTION: This variable specifies the type of database we want to connect to. In this case, it’s set to MySQL, indicating that the application will connect to a MySQL database.

  • DB_HOST: This variable defines the host or IP address of the database server. The value 127.0.0.1 refers to the local machine, indicating that the database server is running on the same machine as the Laravel application.

  • DB_PORT: This variable specifies the port number on which the database server is listening. The value 3306 is the default port for MySQL.

  • DB_DATABASE: This variable specifies the name of the database we want to connect to. In this case, it’s set to Laravel.

  • DB_USERNAME: This variable represents the username used to authenticate and access the database server. The value root indicates that the application will connect using the root user. In a production environment, it’s recommended to use a dedicated database user with restricted privileges.

  • DB_PASSWORD: This variable stores the password associated with the username specified in DB_USERNAME. In this example, the password field is left empty, indicating that no password is set for the root user. In a production environment, it’s highly recommended to set a strong password for database security.

Verification of updated configurations

Every time changes are made to the .env file, new configurations need to be reloaded. Rerunning (php artisan serve) can be utilized to reload updated configurations. After the successful setup of the database, users can verify database connection success using the following steps:

Connection verification via cmd
Connection verification via cmd

The output of the widget can be observed by using the widget below. After executing the widget, follow these steps:

  1. Open the terminal and press “Ctrl + C.”

  2. Execute the following command: php artisan tinker.

  3. Run DB::connection()->getPdo();.

Bud1�icdsclboolpublicdsclbool	resourcesdsclboolroutesdsclboolstoragedsclbool @� @� @� @E�DSDB ` @� @� @
Output of the php artisan tinker command

Note:  If Connection_Status in the results provides an IP, then the database is successfully configured. Otherwise, it's not.

Overview of migrations

In Laravel, migrations are an effective way to handle and track different database table changes. Developers can create, update, and drop tables with their constraints with the help of Laravel migrations code. Laravel migrations are situated in the database/migrations directory with the .php extension.

Introduction to migrations setup

Laravel Artisan CLI provides a way to create new migrations.

php artisan make:migration create_contacts_table
Migration creation for a contacts table

The command above will create a migration in the database/migrations directory with a .php file named 2014_10_12_100000_create_contacts_table. This file describes the basic configurations of columns and their constraints.

The coding widget below can be utilized to practice migration creation. Learners need to adopt the following steps after executing the code:

  1. After successful configuration installation, press “Ctrl + C.”

  2. Access the terminal and run php artisan make:migration create_contacts_table.

Bud1�icdsclboolpublicdsclbool	resourcesdsclboolroutesdsclboolstoragedsclbool @� @� @� @E�DSDB ` @� @� @
Command for creation of migrations

The migrations file in Laravel consists of two methods: up() and down(). In the up() method, table creation-related constraints, data types, and lengths are defined. The down() method is responsible for rolling back the table definitions created by the up() method.

In Laravel, the Schema class is used in migrations to define and modify database tables. Every migration file contains a $table object representing a table instance. The appropriate way to define table columns is as follows: $table->datatype('column Name',' Column Length')->constrainsts().

Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->string('phoneNumber', 64)->unique();
$table->text('details')->nullable();
$table->timestamps();
});
}
Migrations constraints implementation

In the example above, a total of five different columns are created. The columns and their definitions are as follows:

$table->id(): With the help of the built-in id() function, a column named id with the integer data type and autoincremented constraints will be created.

  • $table->string('phoneNumber',64)->unique(): A column named phoneNumber is created with 64 lengths and unique constraints.

  • $table->text('details')->nullable(): A column named details is created with null values allowed.

  • $table->timestamps(): With the help of the built-in function, two different columns named created_at and updated_at are created that will maintain a log of the time intervals at which other columns are updated or created.

After writing migrations, developers need to run php artisan migrate. By running this command, a blueprint representation of migrations is created in the connected database and its log is maintained in the migrations table.

Example of migrations execution
Example of migrations execution

After the successful execution of the Artisan command, we can verify the mapping of migrations to the actual database schema by going to the connected DBMS. In our case, we use phpMyAdmin.

The output of migrations in phpMyAdmin
The output of migrations in phpMyAdmin

Migrations rollback

Here’s the code to roll back the last migration in Laravel:

php artisan migrate:rollback
Reverting database migrations

This command will revert the last batch of migrations, which includes the most recent migration file. The migration down() method is executed, undoing the changes made in the up() method. For example, if the migration creates a table, the rollback will drop that table. To roll back multiple migrations, we can specify the number of migrations to roll back using the --step option. For example, to roll back the last three migrations, we would use the following command:

php artisan migrate:rollback --step=3
Reverting the last three steps

This command will roll back the last three migrations.

Inserting the foreign key in migration

In relational DBMS (RDBMS), proper relations can’t be mapped between tables without the presence of a foreign key. In Laravel, the following steps can be used for the creation of a foreign key:

  • Step 1: Create the second table with the foreign key of the base table’s primary key. In the example below, contacts_info is the table that will use the contacts table primary ID as a foreign key.

  • Step 2: After the creation of the contacts_info table with the make: migration command, the next step is to add column definitions along with foreign key definitions and constraints.

  • Step 3: After successfully creating the file, a definition of the foreign key needs to be added.

Schema::table('contacts_info', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('contact_id');
$table->foreign('contact_id')->references('contacts')->on('id')>onUpdate('null')>onDelete('cascade');
});
Definition of foreign key migrations

The $table->foreign('contact_id')->references('contacts')->on('id')->onUpdate('null')->onDelete('cascade'); line creates a foreign key constraint on the contact_id column. The foreign key constraint ensures that the contact_id column can only contain values that exist in the id column of the contacts table. It also cascade deletes and sets null on an update from the contacts table to the contacts_info table. This means that if any row in the contacts table is deleted, its counterpart (a primary key as a foreign key) in the contacts_info table is also removed. Lastly, if any row in the contacts table is updated, its counterpart will be set to null, or the foreign key will be set to null.

Bud1�icdsclboolpublicdsclbool	resourcesdsclboolroutesdsclboolstoragedsclbool @� @� @� @E�DSDB ` @� @� @
Migrations creation

We can use the widget above to practice Larvel migrations after executing the code. After successful configuration of the installation, press “Ctrl + C.” Afterward, move to the terminal and follow the steps given below.

  • Step 1: Roll back the most recent migration using php artisan migrate:rollback --step=1, which will undo the creation of the contacts table.

  • Step 2: Add new column definitions to the contacts table. For example, a new country_name column needs to be inserted into the database table. To accomplish this, a new column definition can be inserted into the up() function. The syntax for the definition is $table->string('country_name')->nullable();.

  • Step 3: After adding the country_name definition to the contacts migrations, run php artisan migrate.

  • Step 4: After migration, run php artisan tinker after pressing "Ctrl + C.”

  • Step 5: Lastly, run \DB::table('show create table contacts') in the terminal.

Following these steps will do the following:

  • Roll back the most recent migration, which will undo the creation of the contacts table.

  • Add new column definitions to the contacts table.

  • Migrate the changes to the database.

  • Enter the Laravel Tinker console.

  • Run the \DB::table('show create table contacts') command, which will show the create table statement for the contacts table.

By running the (php artisan migrate) migration command, Laravel will execute this migration file, creating the contacts table in the connected database. If the migration needs to be rolled back, the down() method will be executed, dropping the contacts table.

In this lesson, we introduced the concept of adding migrations in Laravel. We got an introductory overview of setting up databases in phpMyAdmin, managing environment variables in Laravel, and performing database migrations.