Using Database in a Laravel Application

How Laravel connect to your Database

How Laravel connect to your Database

Configurations

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

Migrations

Database: Migrations - Laravel 12.x - The PHP Framework For Web Artisans

A migration makes structural changes to the database

<aside> 💡

Migration commands

</aside>

<aside> 💡

Conventions for naming migrations:

  1. Creation of a table:

    create_[table-name]_table

  2. Adding a column to an existing table:

    add_[column-name]_column_to_[table-name]_table

  3. Renaming an existing column in an existing table:

    rename_[column-name]_column_in_[table-name]_table

</aside>

Example for Table Creation Migration

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');
    }
};

Example for Adding a Column to an Existing Table Migration

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');
        });
    }
};

Example for Renaming an Existing Column in an Existing Table

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');
        });
    }
};