Laravel Eloquent Models

Laravel Eloquent Models

Eloquent is Laravel's built-in ORM. Each database table has a corresponding Model that you use to interact with that table.

1 - Creating a Model

php artisan make:model Post
php artisan make:model Post -mfsc  // with migration, factory, seeder, controller

2 - Model Conventions & Configuration

namespace App\Models;

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

class Post extends Model
{
    use SoftDeletes;

    // Columns allowed for mass assignment
    protected $fillable = ['title', 'slug', 'body', 'published'];

    // Cast types automatically
    protected function casts(): array
    {
        return [
            'published'    => 'boolean',
            'published_at' => 'datetime',
            'metadata'     => 'array',
        ];
    }
}

3 - CRUD Operations

// Create
$post = Post::create(['title' => 'Hello', 'slug' => 'hello', 'body' => '...']);

// Read
$post  = Post::find(1);
$post  = Post::findOrFail(1);       // throws 404 if not found
$posts = Post::where('published', true)->latest()->get();
$posts = Post::all();

// Update
$post->update(['title' => 'Updated Title']);

// Delete
$post->delete();

// Restore (SoftDeletes)
$post->restore();

4 - Query Scopes

// Define a local scope on the model
public function scopePublished(Builder $query): void
{
    $query->where('published', true)->whereNotNull('published_at');
}

// Usage — chainable like any query builder method
$posts = Post::published()->latest()->paginate(10);