Module 2: The Core Logic

Database, Migrations & The Eloquent ORM.

Storing and Managing Your Data

Welcome to Module 2! Now that you have a working Laravel application, it's time to give it a brain. Nearly every web application needs to store information—user accounts, blog posts, products, comments, and so on. This is where databases come in. In this module, we'll demystify database interactions in Laravel. You'll learn how to connect your app to a database, structure it using powerful "migrations," and interact with your data using Laravel's most beloved feature: the Eloquent ORM.


1Connecting to Your Database

First things first, you need a database and a way for Laravel to talk to it. If you installed XAMPP/MAMP in Module 1, you already have a MySQL database server running. The next step is to create a new, empty database for your project.

  1. Create a Database: Open your web browser and navigate to `http://localhost/phpmyadmin`. This is a graphical tool for managing your databases. Click on the "Databases" tab, enter a name for your new database (e.g., `my_first_app_db`), choose a collation like `utf8mb4_unicode_ci`, and click "Create".
  2. Configure Laravel: Now, you need to tell Laravel how to find this database. Open your project's `.env` file, located in the root directory. This file holds all your environment-specific settings. Find the section that looks like this:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Update these values to match your new database. For a default XAMPP setup, you only need to change the `DB_DATABASE` name. The username is typically `root` with no password.

# ... other settings ...
DB_DATABASE=my_first_app_db
DB_USERNAME=root
DB_PASSWORD=
# ... other settings ...

2Database Migrations: Version Control for Your Schema

Instead of manually creating tables and columns in phpMyAdmin, Laravel uses a far superior method called migrations. A migration is a PHP file that contains instructions for creating or modifying a database table. Think of it as version control (like Git) for your database structure.

Creating Your First Migration

Let's create a migration for a `posts` table that will store blog posts. We'll need columns for a title and the main content. We can use an Artisan command to generate the migration file for us. In your terminal, run:

php artisan make:migration create_posts_table

This creates a new file in the `database/migrations` directory. The filename will be timestamped, like `2025_08_23_183000_create_posts_table.php`. Let's open it and define our table structure inside the `up()` method:

public function up(): void
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id(); // Creates an auto-incrementing primary key 'id'
        $table->string('title'); // Creates a VARCHAR column for the title
        $table->text('content'); // Creates a TEXT column for the post body
        $table->timestamps(); // Creates 'created_at' and 'updated_at' columns
    });
}

Running Migrations

Once your migration is defined, you can execute it to create the table in your database. Run the following Artisan command:

php artisan migrate

Laravel will run all pending migrations. Now, if you go back to phpMyAdmin and look at your `my_first_app_db` database, you'll see a brand new `posts` table with the exact columns we defined! You'll also see some default tables that Laravel includes for users and other features.


3Eloquent ORM: The Fun Part!

Now for the main event: Eloquent. This is Laravel's Object-Relational Mapper (ORM). It allows you to interact with your database tables as if they were PHP objects, completely abstracting away the raw SQL queries.

Creating a Model

For every table in your database, you'll typically have a corresponding Eloquent "Model". A model is a PHP class that represents that table. Let's create a `Post` model for our `posts` table. Use Artisan:

php artisan make:model Post

This creates a new file at `app/Models/Post.php`. By convention, Laravel knows that the `Post` model corresponds to the `posts` table (plural, snake_case). The file is very simple to start:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
}

That's it! We don't need to tell it about the `title` or `content` columns. Eloquent handles that automatically. (For security, we sometimes need to list fillable fields, but we'll cover that later).

CRUD Operations with Eloquent

CRUD stands for Create, Read, Update, and Delete. These are the four basic operations of data persistence. Let's see how easy Eloquent makes them.

To experiment with this, we can use another amazing Artisan tool called `tinker`. It's an interactive command-line shell for your application. Start it by running:

php artisan tinker

Now you can run PHP code directly in your terminal.

1. Create a new post:

$post = new App\Models\Post;
$post->title = 'My First Blog Post';
$post->content = 'This is the amazing content of my very first post!';
$post->save();

That's it! Eloquent creates a new row in the `posts` table.

2. Read (Find) posts:

// Get all posts
$allPosts = App\Models\Post::all();

// Find a specific post by its ID
$foundPost = App\Models\Post::find(1);

3. Update a post:

// First, find the post you want to update
$postToUpdate = App\Models\Post::find(1);

// Change its properties
$postToUpdate->title = 'My Updated Post Title';

// Save the changes to the database
$postToUpdate->save();

4. Delete a post:

// Find the post
$postToDelete = App\Models\Post::find(1);

// Delete it
$postToDelete->delete();