Eloquent Models

Eloquent lets you interact with database tables through PHP model classes.

Syntaxclass Post extends Model { }

Eloquent is Laravel's ORM (Object-Relational Mapper). Each database table has a matching model class. A row becomes an object, and columns become properties.

By convention a Post model maps to a posts table. Generate one with php artisan make:model Post.

Example

Example · php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'body'];
}

When to use it

  • A developer creates a Post model and immediately uses Post::all() to retrieve all records without writing a single SQL statement.
  • A product catalog uses Eloquent's $fillable array to protect the products table from mass-assignment attacks when processing form submissions.
  • A SaaS app defines $casts on the User model so the preferences column is automatically decoded from JSON and the created_at column always returns a Carbon instance.

More examples

Create a model and migration together

The -m flag tells Artisan to generate the migration file alongside the model so both are available immediately.

Example · bash
php artisan make:model Product -m
# Creates app/Models/Product.php and
# database/migrations/xxxx_create_products_table.php

Define fillable, casts, and timestamps

Declares which columns can be mass-assigned and tells Eloquent how to cast raw DB values to PHP types automatically.

Example · php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['name', 'price', 'stock', 'is_active'];

    protected $casts = [
        'price'     => 'decimal:2',
        'is_active' => 'boolean',
        'metadata'  => 'array',
    ];

    // $timestamps = true by default (created_at, updated_at)
}

Basic CRUD operations

Covers all four CRUD operations with Eloquent: create(), find/findOrFail(), update(), and delete().

Example · php
// Create
$p = Product::create(['name' => 'Widget', 'price' => 9.99, 'stock' => 100, 'is_active' => true]);

// Read
$all     = Product::all();
$single  = Product::find(1);
$orFail  = Product::findOrFail(42); // 404 if missing

// Update
$p->update(['price' => 8.99]);

// Delete
$p->delete();

Discussion

  • Be the first to comment on this lesson.