Introduction
When building a dynamic web application, the database plays a very important role. Laravel makes database management easy and clean using migrations.
In this tutorial, we will learn how to configure the database in Laravel and create tables using migrations without writing complex SQL queries.
What is a Migration in Laravel?
A migration is like a version control system for your database.
It allows you to:
- Create tables
- Modify columns
- Roll back changes easily
Instead of writing SQL manually, Laravel lets you define your database structure using PHP.
Step 1: Database Configuration in Laravel
First, open your .env file and update your database details:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_project DB_USERNAME=root DB_PASSWORD=
Make sure the database already exists in phpMyAdmin or your database manager.
Step 2: Create a Migration
To create a new migration, run the following command:
php artisan make:migration create_users_table
Laravel will create a migration file inside:
database/migrations
Step 3: Understanding a Migration File
A typical migration file looks like this:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
Explanation:
up()→ Creates or modifies tablesdown()→ Reverts the changestimestamps()→ Addscreated_atandupdated_atcolumns
Step 4: Run the Migration
To create the table in the database, run:
php artisan migrate
If successful, Laravel will create the table automatically.
Step 5: Rollback a Migration
If something goes wrong, you can undo the migration using:
php artisan migrate:rollback
This will revert the last batch of migrations.
Step 6: Modifying Existing Tables
To add a new column, create a new migration:
php artisan make:migration add_phone_to_users_table
Inside the migration:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('phone')->nullable();
});
}
Run migrate again to apply changes.
Why Use Migrations?
- Keeps database structure consistent
- Easy collaboration in teams
- No need to write raw SQL
- Easy rollback and updates
Conclusion
Laravel migrations provide a clean and organized way to manage your database structure.
Once you understand migrations, working with databases in Laravel becomes much easier and faster.
In the next tutorial, we’ll cover Laravel Models and Eloquent ORM Basics.
Category: Laravel
Tags: #PHP framework, #Introduction to Laravel, #Laravel framework, #Laravel, #Laravel for beginners, #Learn Laravel, #Laravel basics, #Laravel tutorial, #Web development for beginners, #Laravel Setup, #Laravel Tutorial for Beginners, #Laravel Guide, #PHP Laravel Basics, #database, #laravel database, #eloquent orm, #laravel migrations
2 Likes 0 Comments 13 Views
Leave a comment
Leave a Reply