🎯 Learning Objectives
- Understand database migrations
- Create and run migrations
- Define table columns and data types
- Create Eloquent models
- Understand model conventions
📚 What are Migrations?
Migrations are like version control for your database. They allow you to define and share the database schema with your team.
Benefits: Easy rollback, consistent database structure, no manual SQL!
🏗️ Creating Migrations
Generate Migration:
# Create students table migration
php artisan make:migration create_students_table
# Output:
# Created Migration: 2024_12_06_120000_create_students_table.php
# Location: database/migrations/
Migration Structure:
<?php
// database/migrations/2024_12_06_120000_create_students_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations - creates the table
*/
public function up(): void
{
Schema::create('students', function (Blueprint $table) {
$table->id(); // Auto-increment primary key
$table->string('name');
$table->string('email')->unique();
$table->string('phone');
$table->integer('age');
$table->string('course');
$table->timestamps(); // created_at, updated_at
});
}
/**
* Reverse the migrations - drops the table
*/
public function down(): void
{
Schema::dropIfExists('students');
}
};
?>
📊 Column Data Types
| Method | Database Type | Description |
|---|---|---|
| $table->id() | BIGINT UNSIGNED | Auto-increment primary key |
| $table->string('name') | VARCHAR(255) | Text field (max 255 chars) |
| $table->text('description') | TEXT | Long text field |
| $table->integer('age') | INT | Whole number |
| $table->decimal('price', 8, 2) | DECIMAL | Decimal number (8 digits, 2 after point) |
| $table->boolean('active') | TINYINT(1) | True/False |
| $table->date('birth_date') | DATE | Date only (YYYY-MM-DD) |
| $table->timestamps() | TIMESTAMP | created_at & updated_at |
⚙️ Column Modifiers
<?php
Schema::create('students', function (Blueprint $table) {
$table->id();
// Required field (NOT NULL)
$table->string('name')->required();
// Unique value
$table->string('email')->unique();
// Optional field (can be NULL)
$table->string('phone')->nullable();
// Default value
$table->boolean('active')->default(true);
// Multiple modifiers
$table->string('username')->unique()->nullable();
$table->timestamps();
});
?>
▶️ Running Migrations
# Run all pending migrations
php artisan migrate
# Output:
# Migrating: 2024_12_06_120000_create_students_table
# Migrated: 2024_12_06_120000_create_students_table (45.23ms)
# Rollback last migration
php artisan migrate:rollback
# Rollback all migrations
php artisan migrate:reset
# Rollback all and re-run
php artisan migrate:refresh
# Drop all tables and re-migrate (careful!)
php artisan migrate:fresh
🎨 Complete Migration Example
<?php
// Create courses table
php artisan make:migration create_courses_table
// database/migrations/xxxx_create_courses_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('courses', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description')->nullable();
$table->integer('duration_weeks');
$table->decimal('price', 10, 2)->default(0);
$table->boolean('is_active')->default(true);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('courses');
}
};
?>
🏛️ Eloquent Models
Eloquent is Laravel's ORM (Object-Relational Mapping). Models represent database tables and allow you to interact with data using PHP objects.
Creating Models:
# Create Student model
php artisan make:model Student
# Create model WITH migration
php artisan make:model Course -m
# Output:
# Model created successfully: app/Models/Student.php
# Migration: database/migrations/xxxx_create_courses_table.php
📦 Model Structure
<?php
// app/Models/Student.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
use HasFactory;
// Table name (optional - Laravel auto-detects from model name)
protected $table = 'students';
// Primary key (optional - defaults to 'id')
protected $primaryKey = 'id';
// Mass assignable fields (for security)
protected $fillable = [
'name',
'email',
'phone',
'age',
'course'
];
// Hidden fields (won't show in JSON)
protected $hidden = [
'password',
];
// Disable timestamps if table doesn't have them
// public $timestamps = false;
}
?>
📏 Model Naming Conventions
| Model Name | Table Name | Convention |
|---|---|---|
| Student | students | Lowercase, plural |
| Course | courses | Add 's' |
| Category | categories | 'y' becomes 'ies' |
| Person | people | Irregular plural |
💻 Complete Example: Blog System
Step 1: Create Posts Migration & Model
php artisan make:model Post -m
Step 2: Define Migration
<?php
// database/migrations/xxxx_create_posts_table.php
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('slug')->unique();
$table->text('content');
$table->string('author');
$table->integer('views')->default(0);
$table->boolean('published')->default(false);
$table->timestamps();
});
}
?>
Step 3: Run Migration
php artisan migrate
Step 4: Configure Model
<?php
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'title',
'slug',
'content',
'author',
'views',
'published'
];
// Cast to specific types
protected $casts = [
'published' => 'boolean',
'views' => 'integer',
];
}
?>
🔧 Modifying Existing Tables
# Add column to existing table
php artisan make:migration add_address_to_students_table
<?php
public function up(): void
{
Schema::table('students', function (Blueprint $table) {
$table->text('address')->nullable()->after('phone');
});
}
public function down(): void
{
Schema::table('students', function (Blueprint $table) {
$table->dropColumn('address');
});
}
?>
✏️ Practice Exercises
- Create a migration for 'products' table (name, price, stock, description)
- Create a 'categories' migration with name and description
- Run migrations and verify tables in phpMyAdmin
- Create Product and Category models
- Add 'image' column to products table using new migration
- Practice rollback and refresh commands
✅ Today's Deliverable
- ✓ Understand migrations concept
- ✓ Create students table migration
- ✓ Create courses table migration
- ✓ Run migrations successfully
- ✓ Create Student and Course models
- ✓ Configure $fillable property
- ✓ Verify tables exist in phpMyAdmin