SyntaxStudy
Sign Up
Laravel Eloquent ORM Basics and Models
Laravel Beginner 1 min read

Eloquent ORM Basics and Models

Eloquent is Laravel's built-in ActiveRecord ORM. Each database table has a corresponding Model class that is used to interact with that table. Models are plain PHP classes extending Illuminate\Database\Eloquent\Model. By default, Eloquent uses the snake_case plural form of the class name as the table name (User -> users, BlogPost -> blog_posts), though this can be overridden via the $table property. Eloquent provides a fluent query builder interface. Methods like all(), find(), where(), first(), firstOrFail(), get(), and paginate() cover the most common query patterns. Mass assignment is controlled with the $fillable or $guarded properties — $fillable whitelists columns that can be mass assigned, while $guarded blacklists them. Always define one of these to prevent mass assignment vulnerabilities. Model events (creating, created, updating, updated, deleting, deleted, restoring, restored) fire at various points in a model's lifecycle. They can be observed using model observers — classes registered in a service provider that group all event callbacks for a model in one place. The $casts property automatically converts attribute values to specified PHP types, including arrays, booleans, Carbon dates, and custom cast classes.
Example
<?php
// app/Models/Post.php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'title', 'slug', 'body', 'status', 'user_id', 'published_at',
    ];

    protected $casts = [
        'published_at' => 'datetime',
        'is_featured'  => 'boolean',
        'meta'         => 'array',
    ];

    // Scope for published posts
    public function scopePublished($query)
    {
        return $query->where('status', 'published')
                     ->whereNotNull('published_at');
    }

    // Accessor: auto-trim title
    public function getTitleAttribute(string $value): string
    {
        return ucfirst(trim($value));
    }

    // Relationships
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function tags()
    {
        return $this->belongsToMany(Tag::class)->withTimestamps();
    }
}