Migrations are a powerful feature in Laravel that allow you to handle changes to your database schema. With migrations, you can easily apply and rollback these changes as needed. In this tutorial, we will guide you through the process of creating and modifying your database schema using migrations.
To begin, stop the Laravel server and open your terminal. Run the following command to create a new migration file:
php artisan make:migration initial_table_creation
This command will generate a file named 2023_05_11_080724_initial_table_creation.php
(the date and time stamp will vary for you) in the database/migrations
folder.
Next, open the newly created migration file. Inside the up()
function, you can define the structure of your database table. Let’s create a table called dogs
with three columns: an id
, a name
(string), and the timestamp utility columns (created_at
and updated_at
).
Schema::create('dogs', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Once you have defined your table structure, save the file. Now, execute the following command in your terminal:
php artisan migrate
This command will apply any pending migrations, including the one we just created. If you navigate to your database/database.sqlite
file using a database visualization tool such as TablePlus, you will see the newly created dogs
table along with any other tables defined in your migrations.
In case you make a mistake in a migration, you can easily rollback the changes by running the following command:
php artisan migrate:rollback
This will undo the latest migration and revert the changes made to the database.
For more information and advanced usage of migrations, you can refer to the official migrations guide.
Tags: Laravel, migrations, database schema, PHP