Eloquent is Laravel's built-in ORM. Each database table has a corresponding Model that you use to interact with that table.
php artisan make:model Post
php artisan make:model Post -mfsc // with migration, factory, seeder, controller
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',
];
}
}
// 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();
// 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);