Introduction
Laravel is a popular PHP framework known for its elegant syntax and robust features. One of its most powerful features is its database management system, which includes query builders, Eloquent ORM, and migrations. Migrations allow developers to version-control their database schema, making it easy to collaborate with teams and maintain databases in different environments.
In this article, we will explore databases in Laravel, focusing on database configurations, migrations, database factory seeding, and other best practices.
Database Configuration
Before using Laravel's database features, you need to configure your database connection. The configuration file for databases is located in config/database.php. Laravel supports multiple database connections, including MySQL, PostgreSQL, SQLite, and SQL Server.
Setting Up the .env File
Laravel uses an environment file (.env) to store sensitive database credentials. You can set up your database connection by modifying the .env file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password
After updating the .env file, you should run the following command to clear the configuration cache:
php artisan config:clear
Understanding Migrations
Migrations in Laravel provide a version control system for your database schema, allowing you to define and modify tables using PHP instead of raw SQL. This makes database management more structured and easier to track changes across teams, as developers on your project can easily see the history of modifications that was made on your database structure.
Creating Migrations
To create a migration, use the Artisan command. Let us say you would like to create a database table called "products" which holds details about products in your application. your artisan command would be:
php artisan make:migration create_products_table
This will generate a migration file inside the database/migrations directory, which looks like this:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};
You will find two methods in the migration class created above; the 'up' and 'down' methods. The 'up' method creates the table structure into the database using the name (in this case, 'products') which falls in between the 'create' and 'table' keywords in in the previous command above. The down method on the other hand is used to tear down the table structure when specified in the artisan command. Before you proceed to execute the command which would run the migration, you can modify the 'up' method to include all the fields, their data types, default values, position, and other structure that is required for the products table in your application.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description')->nullable();
$table->decimal('price', 8, 2);
$table->boolean('is_published')->default(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};
Running Migrations
Once the migration file is created, apply it using:
php artisan migrate
This command executes all pending migrations, creating or modifying tables as defined in the migration files.
Rolling Back Migrations
If you need to undo the last migration, use:
php artisan migrate:rollback
To reset the entire database schema and re-run all migrations:
php artisan migrate:reset
php artisan migrate
To rollback and re-run migrations in a single step:
php artisan migrate:refresh
Seeding the Database
Laravel also provides a feature called database seeding, which allows you to insert dummy data into the database for testing and development. Seeder files are located in database/seeders.
To create a seeder:
php artisan make:seeder ProductSeeder
A typical seeder file looks like this:
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class ProductSeeder extends Seeder
{
public function run()
{
DB::table('products')->insert([
'name' => 'Sample Product',
'description' => 'This is a sample product.',
'price' => 100.00,
'created_at' => now(),
'updated_at' => now(),
]);
}
}
Run the seeder using:
php artisan db:seed --class=ProductSeeder
To run all seeders defined in DatabaseSeeder.php, use:
php artisan db:seed
Factories and Seeders for Testing
Laravel provides model factories that allow you to generate fake data using the Faker library. First, create a factory:
php artisan make:factory ProductFactory --model=Product
Modify the factory file:
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Product;
class ProductFactory extends Factory
{
protected $model = Product::class;
public function definition()
{
return [
'name' => $this->faker->word,
'description' => $this->faker->sentence,
'price' => $this->faker->randomFloat(2, 10, 500),
];
}
}
Use the factory in the seeder:
use App\Models\Product;
//...
public function run(): void
{
Product::factory()->count(50)->create();
}
Run the seeder:
php artisan db:seed
Best Practices
Use Descriptive Migration Names – Always name migrations clearly (e.g., create_orders_table instead of new_table).
Keep Migrations Modular – Avoid modifying multiple tables in a single migration file.
Use Factories for Testing – Generate dummy data efficiently using factories instead of manually inserting records.
Backup Before Migration – Before running destructive commands like migrate:reset, ensure you have a backup of your database.
Run Migrations in CI/CD Pipelines – Automate migrations using CI/CD workflows to keep environments synchronized.
Conclusion
Laravel's database management system, powered by migrations, seeders, and factories, provides a structured and maintainable way to handle databases. By leveraging migrations, you can track schema changes effectively, ensuring smooth collaboration across development teams. Understanding and implementing Laravel migrations properly will greatly enhance the efficiency and scalability of your applications.
Top comments (0)