In Laravel, database configuration and migration are fundamental tasks for setting up and managing your application’s database. Here’s how you can handle both:
1. Database Configuration
Before you can run migrations, you need to configure your database in Laravel. This is done in the .env
file located in your project’s root directory. Here’s a typical configuration for a MySQL database:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password
Make sure to replace your_database_name
, your_database_username
, and your_database_password
with your actual database details. Laravel supports other databases like PostgreSQL, SQLite, and SQL Server as well.
2. Migration Basics
Migrations are like version control for your database, allowing you to modify and share the application’s database schema. You can generate a new migration file using the Artisan command line tool provided by Laravel.
Creating a Migration
To create a migration, use the make:migration
command:
php artisan make:migration create_users_table --create=users
This command creates a new migration for a users
table. The migration file will be located in the database/migrations
directory.
Migration Structure
A migration file contains two methods: up()
and down()
. up()
is used to add new tables, columns, or indexes to your database, while down()
should reverse the operations performed by the up()
method.
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
3. Running Migrations
To apply the migrations, use:
php artisan migrate
This command will execute the up()
method in your migrations that haven’t been run yet.
4. Rolling Back Migrations
If you need to undo a migration, you can use:
php artisan migrate:rollback
This command will call the down()
method for the last batch of migrations that were applied.
5. Database Seeding
After migrating, you might want to populate your database with initial data. This can be done using seeders.
Creating a Seeder
Generate a seeder via Artisan:
php artisan make:seeder UsersTableSeeder
Then, you can define the data insertion within the run()
method of your seeder:
public function run()
{
DB::table('users')->insert([
'name' => 'Example User',
'email' => 'user@example.com',
'password' => Hash::make('password'),
]);
}
Running Seeders
Execute the seeder using:
php artisan db:seed --class=UsersTableSeeder
This command populates the users
table with the specified data.
6. Migration and Seeding Together
You can also migrate and seed your database in one command:
php artisan migrate --seed
This is helpful for setting up a fresh database with all the necessary schema and data together.