The Best Laravel Tips & Tricks for Migrations

Websolutionstuff | Oct-23-2023 | Categories : Laravel MySQL

Migrations are an essential part of any Laravel project, allowing developers to easily manage and update their database structure. However, they can also be a source of frustration if not done correctly. In this article, we will discuss some of the best tips for Laravel migrations to help you streamline your database management process.

In this article, I'm excited to share some of the best Laravel tips and tricks for migrations—those crucial operations that shape and maintain the database structure of your application.

Laravel migrations are a powerful tool that makes database management a breeze, offering elegant solutions for schema changes and data seeding.

With a focus on Laravel migration tips and tricks, we'll dive into techniques that can streamline your development process, improve your database efficiency, and make your code cleaner and more maintainable.

Let's unlock the secrets of seamless database operations with Larave, tips & tricks for laravel migrations, quick laravel tips: migrations, laravel daily tips and tricks, 10 Tips for Migrating with Laravel 9/10.

Order of Migrations

To change the order of database migrations, simply rename the migration file's timestamp. For example, you can change "2023_10_15_070443_create_posts_table.php" to "2023_07_10_070443_create_posts_table.php" by modifying the timestamp from "2023_10_04" to "2023_10_10".

This is because migrations are executed in alphabetical order

 

Migration fields with timezones

Laravel migrations, there are two methods for adding timestamp columns to your database tables: timestamps() and timestampsTz(). These methods allow you to work with timestamps in different ways, depending on your application's needs.

  1. timestamps(): This method adds two timestamp columns, created_at and updated_at, to your table. These columns use the default timezone configured in your Laravel application (usually UTC). For most cases, this is sufficient and works well.

    Example: 

    $table->timestamps();

     

  2. timestampsTz(): This method is similar to timestamps() but allows you to specify a custom timezone for the timestamp columns. If your application needs to work with timestamps in a specific timezone, you can use timestampsTz() to ensure that the timestamps are recorded and retrieved in that timezone.

    Example:

    $table->timestampsTz('your_timezone');

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

     

Database migrations column types

Here are a few examples of interesting column types you can use in migrations.

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

 

Default Timestamp

While creating migrations, you can use the timestamp() column type with the useCurrent() and useCurrentOnUpdate() options. This will set CURRENT_TIMESTAMP as the default value for the column.

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

 

Migration Status

If you want to check which migrations have been executed and which ones are pending, there's no need to manually inspect the "migrations" table in your database. Instead, you can simply run the php artisan migrate:status command.

Migration name .......................................................................... Batch / Status
2014_10_12_000000_create_users_table ........................................................... [1] Ran
2014_10_12_100000_create_password_resets_table ................................................. [1] Ran
2019_08_19_000000_create_failed_jobs_table ..................................................... [1] Ran

 

Create Migration with Spaces

When using the make:migration command, you don't necessarily have to use underscores (_) between different parts of the migration name, such as in "create_posts_table." Alternatively, you can enclose the name in quotes and use spaces instead of underscores, like this:

php artisan make:migration "Create Posts Table"

This approach can make your migration names more human-readable and may help improve the clarity of your migration filenames.

 

 

Create Column after Another Column

When adding a new column to an existing table in a Laravel migration, you're correct that it doesn't have to be placed at the end of the column list. You can specify the position of the new column by using the after method. Here's how you can do it:

// after
Schema::table('users', function (Blueprint $table) {
    // Other columns...

    $table->string('phone_number')->after('email');
});

// before

Schema::table('users', function (Blueprint $table) {
    // Other columns...

    $table->string('phone_number')->before('created_at');
});

Also the after() method can now be used to add multiple fields:

Schema::table('users', function (Blueprint $table) {
    $table->after('remember_token', function ($table){
        $table->string('phone_number')->nullable();
        $table->text('address')->nullable();
    });
});

To make a column the first in your table, you can use the first method in your Laravel migration. Here's how you can do it:

Schema::table('your_table_name', function (Blueprint $table) {
    // Other columns...

    $table->string('new_column')->first();
});

 

Make migration for an existing table

If you're creating a migration for an existing table, and you want Laravel to generate the Schema::table() code for you, simply add "_in_xxxxx_table" or "_to_xxxxx_table" at the end of your migration file's name, or you can also specify the "--table" parameter. For example, running php artisan change_fields_posts_table generates an empty migration class

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

But add in_xxxxx_table php artisan make:migration change_fields_in_posts_table and it generates class with Schema::table() pre-filled.

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

Also you can specify --table parameter php artisan make:migration change_column_name --table=posts

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

 


You might also like:

Recommended Post
Featured Post
How to Integrate Cashfree Payment Gateway in Laravel 10
How to Integrate Cashfree Paym...

Hello developers! Today, we're about to embark on a journey to elevate our Laravel applications by integrating...

Read More

Feb-12-2024

How To Create Custom Login Page In Django
How To Create Custom Login Pag...

In this article, we will see how to create a custom login page in django. how to allow user registration, login, an...

Read More

May-14-2022

How To Validate Max File Size Using Javascript
How To Validate Max File Size...

This article will show us how to validate max file size using javascript. Many times we have a requirement to check...

Read More

Aug-03-2020

How To Create Zip File In Laravel 7/8
How To Create Zip File In Lara...

In this tutorial I will give you example of how to create zip file in laravel 7/8. Some times client's have requirme...

Read More

Dec-17-2021