Blog Detail

13

Oct
Top 10 Latest Tips and Tricks for Laravel Migrations cover image

arrow_back Top 10 Latest Tips and Tricks for Laravel Migrations

Migrations are like version control for your database. It enables your team to establish and share the application’s database schema definition. If you have ever had to tell a teammate to manually add a column to their local database schema after pulling in your changes from source control, you’ve encountered the problem that database migrations solve.
In Laravel, Migration provides a way for easily sharing the schema of the database. It is like building a schema once and then sharing it many times. It gets very beneficial when you have multiple tables and columns as it would reduce the work of generating the tables manually. Here in this article, I will share some awesome tips & tricks related to laravel migrations that many of you don’t know before.

Unsigned Integer

For foreign key migrations instead of integer() use unsignedInteger() type or integer()->unsigned(), otherwise you may get SQL errors.

Schema::create('clients', function (Blueprint $table) {
    $table->unsignedInteger('company_id');
    $table->foreign('company_id')->references('id')->on('companies');
    // ...
});

You can also use unsignedBigInteger() if that other column is bigInteger() type.

Schema::create('clients', function (Blueprint $table) {
    $table->unsignedBigInteger('company_id');
});

Order of Migrations

If you want to change the order of DB migrations, just rename the file’s timestamp, like from

2021_08_04_070443_create_users_table.php 

to

2021_07_04_070443_create_users_table.php

(changed from 2021_08_04 to 2021_07_04).
They run in alphabetical order.

Migration fields with timezones

Did you know that in migrations there are not only timestamps() but also timestampsTz(), for the timezone?

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email');
    $table->timestampsTz();
});

Also, there are columns dateTimeTz(), timeTz(), timestampTz(), softDeletesTz().

Database migrations column types

There are interesting column types for migrations, here are a few examples.

$table->geometry('positions');
$table->ipAddress('visitor');
$table->macAddress('device');
$table->point('position');
$table->uuid('id');

See all column types on the official documentation.

Default Timestamp

While creating migrations, you can use timestamp() column type with option useCurrent() and useCurrentOnUpdate(), it will set CURRENT_TIMESTAMP as default value.

$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrentOnUpdate();

Migration Status

If you want to check what migrations are executed or not yet, no need to look at the database migrations table, you can launch the php artisan migrate:status command.

Example result:
+------+------------------------------------------------+-------+
| Ran? | Migration                                      | Batch |
+------+------------------------------------------------+-------+
| Yes  | 2021_10_12_000000_create_users_table           | 1     |
| Yes  | 2021_10_12_100000_create_password_resets_table | 1     |
| No   | 2021_12_19_000000_create_failed_jobs_table     |       |
+------+------------------------------------------------+-------+

Create Migration with Spaces

When typing make:migration command, you don’t necessarily have to use the underscore _ symbol between parts, like create_transactions_table.
Now you can wrap your new migration name in quotes to avoid typing those underscores/dashes, And it still auto-fills the table name and correct statement type.

// This works
php artisan make:migration create_posts_table

// But this works too
php artisan make:migration "create posts table"

Output SQL before running migrations

When typing migrate –pretend command, you get the SQL query that will be executed in the terminal. It’s an interesting way to debug SQL if necessary.

// Artisan command
php artisan migrate --pretend

Create Column after Another Column

Notice: Only MySQL

If you’re adding a new column to the existing table, it doesn’t necessarily have to become the last in the list. You can specify after which column it should be created:

Schema::table('clients', function (Blueprint $table) {
    $table->string('phone')->after('email');
});

If you’re adding a new column to the existing table, it doesn’t necessarily have to become the last in the list. You can specify before which column it should be created:

Schema::table('clients', function (Blueprint $table) {
    $table->string('phone')->before('created_at');
});

If you want your column to be the first in your table, then use the first method.

Schema::table('clients', function (Blueprint $table) {
    $table->string('uuid')->first();
});

Make migration for an existing table

If you wanted to make a migration for an existing table, and you want Laravel to generate the Schema::table() for you, then add _in_xxxxx_table at the end, or specify –table parameter. If you execute the php artisan change_fields_products_table command, then it will generate an empty class.

class ChangeFieldsProductsTable extends Migration
{
    public function up()
    {
        //
    }
}

But if you add in_xxxxx_table in the above command, like php artisan make:migration change_fields_in_products_table then it generates class with Schemma::table() pre-filed.

class ChangeFieldsProductsTable extends Migration
{
    public function up()
    {
        Schema::table('products', function (Blueprint $table) {
            //
        })
    };
}

Also, you can define –table parameter php artisan make:migration whatever_you_want --table=products

class WhateverYouWant extends Migration
{
    public function up()
    {
        Schema::table('products', function (Blueprint $table) {
            //
        })
    };
}

These are some beneficial tips and tricks related to laravel migrations, I hope that by following these tips you will enhance the performance of your code and usability. If you like them then please share your views on our Facebook, Twitter, or Instagram.

Facebook : https://www.facebook.com/CodeBrisk

Twitter: https://twitter.com/CodeBrisk

Instagram: https://www.instagram.com/codebrisk/

Published at : 13-10-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project