How Laravel connect to your Database
Item in .env |
Configuration File | Description |
---|---|---|
DB_CONNECTION |
config/database.php |
Which database software to use (driver) |
DB_DATABASE |
config/database.php |
Name of the database to use |
DB_PASSWORD |
config/database.php |
Password for database connection |
DB_USERNAME |
config/database.php |
Username for database connection |
DB_PORT |
config/database.php |
Port for database connection |
DB_HOST |
config/database.php |
Host IP for database connection |
Database: Migrations - Laravel 12.x - The PHP Framework For Web Artisans
<aside> 💡
Migration commands
Applying migrations
php artisan migrate
Creating a new migration
php artisan make:migration
Rolling back the last ran migration
php artisan migrate:rollback
</aside>
Migration
class
up
and down
method:
up
makes the changes to database according to the migrationdown
rolls back changes to database made by the migrationdatabase/migrations
folder<aside> 💡
Conventions for naming migrations:
Creation of a table:
create_[table-name]_table
Adding a column to an existing table:
add_[column-name]_column_to_[table-name]_table
Renaming an existing column in an existing table:
rename_[column-name]_column_in_[table-name]_table
</aside>
php artisan make:migration create_books_table
<?php
use Illuminate\\Database\\Migrations\\Migration;
use Illuminate\\Database\\Schema\\Blueprint;
use Illuminate\\Support\\Facades\\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('books', function (Blueprint $table) {
$table->id();
$table->string("name");
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('books');
}
};
php artisan make:migration add_publication_year_column_to_books_table
<?php
use Illuminate\\Database\\Migrations\\Migration;
use Illuminate\\Database\\Schema\\Blueprint;
use Illuminate\\Support\\Facades\\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('books', function (Blueprint $table) {
$table->string('publication_year')->after("id")->nullable();
});
}
public function down(): void
{
Schema::table('books', function (Blueprint $table) {
$table->dropColumn('publication_year');
});
}
};
php artisan make:migration rename_name_column_in_books_table
<?php
use Illuminate\\Database\\Migrations\\Migration;
use Illuminate\\Database\\Schema\\Blueprint;
use Illuminate\\Support\\Facades\\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('books', function (Blueprint $table) {
$table->renameColumn('name', 'title');
});
}
public function down(): void
{
Schema::table('books', function (Blueprint $table) {
$table->renameColumn('title', 'name');
});
}
};