Laravel Eloquent ORM

Laravel Eloquent is the ORM (object-relational mapper) that lets you work with database tables as PHP classes. Each table has a model, each row becomes a model object, and queries read almost like English.

Creating an Eloquent Model

By convention, the Post model maps to the posts table. $fillable lists columns allowed in mass assignment; casts convert columns to PHP types.

<?php
namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

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

    protected function casts(): array
    {
        return ['published_at' => 'datetime'];
    }
}
(Model App\Models\Post <-> table posts)

Retrieving Records

<?php
$all = Post::all();
$post = Post::find(1);
$post = Post::findOrFail(1);           // 404 if missing
$latest = Post::where('status', 'published')
    ->whereNotNull('published_at')
    ->orderByDesc('published_at')
    ->take(5)
    ->get();
$count = Post::where('views', '>', 100)->count();
$titles = Post::pluck('title');

echo $post->title, " | ", $latest->count(), " | ", $count;
Hello Laravel | 5 | 12

Inserting, Updating and Deleting

<?php
$post = Post::create([
    'title' => 'Eloquent Basics',
    'slug' => 'eloquent-basics',
    'body' => 'Models make databases easy.',
]);
echo $post->id, "\n";

$post->title = 'Eloquent Basics (Updated)';
$post->save();

Post::where('status', 'draft')->update(['status' => 'published']);
$post->delete();

$tag = Tag::firstOrCreate(['name' => 'laravel']);
echo $tag->wasRecentlyCreated ? 'new tag' : 'existing tag';
16
existing tag

Query Scopes and Accessors

Local scopes package reusable query conditions. Accessors create computed attributes.

<?php
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;

class Post extends Model
{
    public function scopePublished(Builder $query): void
    {
        $query->where('status', 'published');
    }

    protected function excerpt(): Attribute
    {
        return Attribute::get(fn () => str($this->body)->limit(40));
    }
}

$posts = Post::published()->latest()->get();
echo $posts->first()->excerpt;
Models make databases easy. You can q...

Pagination

paginate() splits results into pages and returns links you can render in Blade with {{ $posts->links() }}.

<?php
$posts = Post::published()->latest()->paginate(10);
echo $posts->currentPage(), "/", $posts->lastPage(), " total=", $posts->total();
1/3 total=27

Frequently asked questions

What is mass assignment in Laravel?

Passing an array of attributes to create() or update(). Only columns in $fillable (or not in $guarded) are allowed, which stops users from setting fields like is_admin.

What is the difference between find and findOrFail?

find returns null when no record exists; findOrFail throws a ModelNotFoundException that Laravel turns into a 404 page.

What is the difference between get and all in Eloquent?

all() fetches every row with no conditions. get() runs the query you built with where, orderBy and so on.