Eloquent ORM: Fresh Project, Table Schemas, Models & Dynamic Blade Queries
In this third laboratory phase of Web Development 3, you will build a persistent, dynamic database application in a brand-new Laravel 11 project. Rather than writing repetitive and error-prone raw SQL strings (SELECT * FROM products), you will master Laravel's Eloquent Object-Relational Mapper (ORM), table schema design with Artisan, mass-assignment protection, and database seeders.
For this activity, you are creating a brand-new Laravel 11 project from scratch (campus-gear). You do not need to migrate or carry over code from your previous laboratory tasks.
Module Overview & Learning Objectives
composer create-project) dedicated solely to database operations.string, decimal, boolean).$fillable mass-assignment protection and attribute casts.php artisan tinker REPL.Conceptual Foundation: Native SQL vs. Laravel Eloquent
In native PHP development, database interaction requires manual PDO queries, manual error-handling loops, and risky string concatenations that expose applications to SQL Injection vulnerabilities. Eloquent bridges your relational database with clean Object-Oriented PHP:
Native PHP (Legacy PDO)
Manual SQLRequires typing raw SQL strings, manually executing statements, checking rows, and fetching assoc arrays:
$stmt->execute();
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
Laravel Eloquent ORM
ActiveRecordModels represent database tables. Queries are expressive, chainable, and automatically prepared with PDO parameter binding:
->latest()
->get();
Step-by-Step Lab Guide: The Campus Gear Catalog
10 MilestonesScaffold a Brand-New Laravel 11 Project (composer create-project)
Open your terminal or command prompt in your projects folder (e.g., Documents/Programming) and generate a fresh Laravel 11 project named campus-gear:
composer create-project laravel/laravel campus-gear cd campus-gear
campus-gear folder in Visual Studio Code (code .). All subsequent commands in this guide will be run inside this folder.Database Environment Configuration (.env & SQLite / MySQL)
Inside your new campus-gear project, Laravel 11 defaults to zero-configuration SQLite, which stores your database in a lightweight local file inside database/database.sqlite. You can also connect to MySQL (e.g., via XAMPP).
DB_CONNECTION=sqlite # In Laravel 11, SQLite is the default and auto-creates the database file!
Generating the Table Schema with Artisan
Migrations serve as version control for your database schema. Use the Artisan CLI to scaffold a migration for a new products table:
php artisan make:migration create_products_table --create=products
Now open the generated file inside database/migrations/xxxx_xx_xx_create_products_table.php and define the columns in the up() method:
<?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('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('sku')->unique();
$table->string('category');
$table->decimal('price', 8, 2);
$table->integer('stock')->default(0);
$table->text('description')->nullable();
$table->boolean('is_available')->default(true);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('products');
}
};Running Table Schemas with Artisan
Execute your migrations to build the physical database tables:
php artisan migrate
php artisan migrate:status to verify that all batch runs report [Ran].Creating the Eloquent Model & Mass-Assignment Protection
Generate the Model class representing the products table:
php artisan make:model Product
Open app/Models/Product.php. Add the $fillable array to whitelist attributes allowed during Product::create():
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name',
'sku',
'category',
'price',
'stock',
'description',
'is_available'
];
protected function casts(): array
{
return [
'price' => 'decimal:2',
'stock' => 'integer',
'is_available' => 'boolean',
];
}
}Database Seeding & Interactive Tinker CLI Playground
Create a dedicated Seeder to populate initial mock records:
php artisan make:seeder ProductSeeder
Add mock items in database/seeders/ProductSeeder.php:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Product;
class ProductSeeder extends Seeder
{
public function run(): void
{
Product::create([
'name' => 'Mechanical Keyboard (RGB Blue Switches)',
'sku' => 'TECH-KB-001',
'category' => 'Peripherals',
'price' => 2499.00,
'stock' => 15,
'description' => 'Tactile clicky mechanical keyboard ideal for lab coding sessions.',
'is_available' => true,
]);
Product::create([
'name' => 'Ergonomic Vertical Mouse',
'sku' => 'TECH-MS-002',
'category' => 'Peripherals',
'price' => 1250.50,
'stock' => 28,
'description' => 'Reduces wrist strain during long programming hours.',
'is_available' => true,
]);
Product::create([
'name' => 'USB-C Multiport Docking Station',
'sku' => 'TECH-HUB-004',
'category' => 'Accessories',
'price' => 3100.00,
'stock' => 0,
'description' => 'HDMI 4K, Gigabit Ethernet, 100W PD passthrough.',
'is_available' => false,
]);
}
}Now run the seeder command and test your queries inside tinker:
php artisan db:seed --class=ProductSeeder
# Open the interactive interactive PHP REPL:
php artisan tinker
# Inside tinker, run these test Eloquent queries:
> App\Models\Product::count();
=> 3
> App\Models\Product::where('is_available', true)->pluck('name');
=> ["Mechanical Keyboard (RGB Blue Switches)", "Ergonomic Vertical Mouse"]Creating the Controller with Eloquent Queries
Scaffold the HTTP Controller using Artisan:
php artisan make:controller ProductController
Open app/Http/Controllers/ProductController.php and write the methods to query Eloquent models:
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index()
{
// Eloquent query fetching newest records
$products = Product::latest()->get();
return view('products.index', [
'products' => $products,
'totalCount' => Product::count(),
'inStockCount' => Product::where('is_available', true)->count()
]);
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'sku' => 'required|string|unique:products,sku',
'category' => 'required|string',
'price' => 'required|numeric|min:0',
'stock' => 'required|integer|min:0',
'description' => 'nullable|string',
]);
$validated['is_available'] = $request->has('is_available');
// Safe Mass Assignment via Eloquent
Product::create($validated);
return redirect()->route('products.index')
->with('success', 'Product created successfully!');
}
}Configuring Routes in routes/web.php
Open routes/web.php and wire the controller methods to URL endpoints:
use App\Http\Controllers\ProductController;
Route::get('/', function () {
return redirect()->route('products.index');
});
Route::get('/products', [ProductController::class, 'index'])->name('products.index');
Route::post('/products', [ProductController::class, 'store'])->name('products.store');Designing the Master Layout & Dynamic Blade View
First, establish a clean master layout shell inside your new project at resources/views/layouts/app.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@yield('title', 'Campus Gear')</title>
<style>
body { font-family: system-ui, -apple-system, sans-serif; background: #f8fafc; color: #1e293b; margin: 0; padding: 30px 16px; }
.container { max-width: 920px; margin: 0 auto; }
</style>
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>Next, create the folder resources/views/products/ and save index.blade.php. It extends layouts.app and loops over the Eloquent records using @forelse:
@extends('layouts.app')
@section('title', 'Campus Inventory - Eloquent ORM')
@section('content')
<div class="product-catalog">
<h1>Campus Gear Inventory</h1>
<p>Total Items: {{ $totalCount }} | In Stock: {{ $inStockCount }}</p>
<!-- Dynamic Eloquent Loop -->
<table>
@forelse($products as $product)
<tr>
<td>{{ $product->sku }}</td>
<td>{{ $product->name }}</td>
<td>₱{{ number_format($product->price, 2) }}</td>
<td>
@if($product->is_available)
<span class="badge-success">● {{ $product->stock }} in stock</span>
@else
<span class="badge-danger">✕ Unavailable</span>
@endif
</td>
</tr>
@empty
<tr><td colspan="4">No records found.</td></tr>
@endforelse
</table>
</div>
@endsectionLaunch Local Dev Server & Live Browser Verification
Start your local Laravel development server and open the live product catalog in your browser:
php artisan serve
Troubleshooting Common Student Errors
Cause: Attempting to save form input with Product::create() without adding the columns to $fillable in app/Models/Product.php.
Cause: You created the migration file but forgot to run php artisan migrate. Make sure all migration batches show '[Ran]'.
Required Laboratory Submission Items
Submit the following 4 deliverables to the course LMS or submit directly to your instructor:
1. Migration & Model Screenshots
Capture terminal output showing php artisan migrate:status alongside your app/Models/Product.php file.
2. Artisan Tinker Query Proof
Terminal screenshot demonstrating interactive queries inside Tinker: Product::all() and Product::count().
3. Live Browser Demonstration
Short video or animated screen capture navigating to http://127.0.0.1:8000/products displaying dynamic records loaded from the database.
4. GitHub Repository Link
Public repository containing your migration files, Product model, controller, and Blade views with clean git commit messages.