How to Make Laravel Migration Order After More Readable
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Click here for the table of contents for Laravel articles
When using the 'after' in Laravel migration, it can be difficult to achieve the desired order of columns, so I wrote about how to make it more readable.
[Related Article] How to Create a Database in Laravel (Migration)
What is 'after' in Migration?
You can add a column after a specific column
Schema::table('posts', function (Blueprint $table) {
$table->string('name')->after('id');
});
If you want to insert a name column after the id in the posts table, you can write it in the migration file like this.
Issues
It is difficult to achieve the desired order when adding multiple columns.
For example,
①name
②title
③photo
If you want to enter them in the above order,
Schema::table('posts', function (Blueprint $table) {
$table->string('name')->after('id'); //1
$table->string('title')->after('id'); //2
$table->string('photo')->after('id'); //3
});
When you write this, the columns are added in the order of ③②①.
Solution
Write in reverse! lol
Schema::table('posts', function (Blueprint $table) {
$table->string('photo')->after('id'); //3
$table->string('title')->after('id'); //2
$table->string('name')->after('id'); //1
});
Since the column addition process in the migration is executed from the top, the first column written will be pushed out and pushed further to the right.
It's a brute force method.
How to Set Up Periodic Execution (Scheduler) in Laravel
When to Use Laravel's make:command?
Summary
That's all. I've settled with this result after thinking carefully.
If you have a better way, please let me know.
For feedback or complaints, please contact me via Twitter DM.
That's it!
Popular Articles
Deploying a PHP 7.4 + Laravel 6 Project to AWS EC2
Implementing Breadcrumbs in Laravel with laravel-breadcrumbs