Laravel 9.* create tags table using Migrations

Lyubomir Filipov
3 min readNov 27, 2022

--

In order to proceed you should have:
- Laravel installed + Backpack admin (teaching purposes)
- virtual host ready for you
- xampp setup or other web server
- composer installed

# STEP 1. create migration

Note: In the older version there was a way to provide the schema as parameter like this

php artisan make:migration:schema create_tags_table — model=0 — schema=”name:string:unique,slug:string:unique”

ERROR There are no commands defined in the “make:migration” namespace. Did you mean one of these?

If you check the available commands

You will see that schema parameter is no longer supported. So we will go with the old fashioned way.

php artisan make:migration create_tags_table

The command will create a new file inside our “migrations”folder.

# STEP 2. Alter migration file

The migration file has two methods. up() — responsible for creation of the table and down() — responsible for removing the table. You should always make sure that the two methods will serve their purpose.

Using of migrations allows you to have a quick and easy setup for your projects making sure that noone is making adjustments to the database by hand. You should avoid such behavior ot any costs! Having all documented with migrations makes your life way easier when you start investigating why certain feature was created.

Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('slug')->unique();
$table->timestamps();
});

Copy the code above inside the up method. It adds two fields to the table name and slug and both of them are utilizing the unique index.

More about indexes you could find here.

# STEP 3. Run the migration command

php artisan migrate

The command will check DB and see are there any migration files which are not yet run. If so it will run them and store a mark in the DB.

Example of the created DB

Migrations table that you could use for reference to check did migrations run successfully.

migrations table

Note: You could revert migrations. You could do that by

php artisan migrate:rollback

The command will revert the latest migration. It will run the down method and delete it. You could see from the screenshots that it removed the row from migrations table and also it dropped the table.

--

--