Migrations

Migrations

A migration displays a table in a database. What’s special about this is that this is written in PHP and you can directly access it from your project folder / code editor.
In Laravel it will automatically create them for you to a certain extend. You can find all these migrations in the following directory: database->migrations.

There are a few different commands you can run to execute these migration files.

Bash
php artisan migrate:fresh // Drop all tables and re-run all migrations

php artisan migrate:install // Create the migration repository

php artisan migrate:refresh // Reset and re-run all migrations

php artisan migrate:reset // Rollback all database migrations

php artisan migrate:rollback // Rollback the last database migration

php artisan migrate:status // Show the status of each migration

The main ones you will probably use are:

  • php artisan migrate:fresh
  • php artisan migrate:refresh
  • php artisan migrate:reset

Now if you want to run the new or changed migrations then you can run:

Bash
php artisan migrate

If you want to create a new migration you call this command:

Bash
php artisan make:migration

Now if you look at a migration file in your code editor you notice 2 functions:

up

PHP
public function up(): void
{

}

Now in here you will put all the code that you want / need when you run the migrations. For example:

PHP
public function up(): void
{
    Schema::create('job_listings', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->string('salary');
        $table->timestamps();
    });
}

What this does once the migration is run it will create a “job-listings” table and inside the table a row for: id, title, salary and timestamps.

down

PHP
public function down(): void
{
  
}

This is for when you want to reverse the migration. For example:

PHP
public function down(): void
{
    Schema::dropIfExists('job_listings');
}

This drops (deletes) the table “job_listings” and all the content inside it.

Tags: