Eloquent ORM
LaravelEloquent is Laravel's built-in ORM. It maps database tables to PHP classes (Models) and lets you interact with your database using clean, expressive PHP code.
Creating a Model
Terminal
php artisan make:model Post
# Creates: app/Models/Post.phpapp/Models/Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
// Columns that can be mass-assigned
protected $fillable = ['title', 'slug', 'body', 'user_id', 'published'];
// Or: protect everything except these
// protected $guarded = ['id'];
// Type casting
protected $casts = [
'published' => 'boolean',
'published_at' => 'datetime',
'settings' => 'array',
];
}
?>CRUD Operations
PHP — Create
<?php
// Create
$post = Post::create([
'title' => 'My First Post',
'slug' => 'my-first-post',
'body' => 'Hello World!',
'user_id' => 1,
]);
// Or
$post = new Post();
$post->title = 'My First Post';
$post->save();
echo $post->id; // Auto-generated ID
?>PHP — Read
<?php
// Get all
$posts = Post::all();
// Find by ID
$post = Post::find(1);
$post = Post::findOrFail(1); // Throws 404 if not found
// Where conditions
$published = Post::where('published', true)->get();
$recent = Post::where('created_at', '>=', now()->subDays(7))->get();
// Multiple conditions
$posts = Post::where('published', true)
->where('user_id', 1)
->orderBy('created_at', 'desc')
->limit(10)
->get();
// First result
$latest = Post::latest()->first();
// Count
$total = Post::count();
$publishedCount = Post::where('published', true)->count();
?>PHP — Update & Delete
<?php
// Update
$post = Post::find(1);
$post->title = 'Updated Title';
$post->save();
// Mass update
Post::where('user_id', 1)->update(['published' => true]);
// Delete
$post = Post::find(1);
$post->delete(); // Soft delete (moves to trash)
// Force delete (permanent)
$post->forceDelete();
// Restore soft-deleted
$post->restore();
// firstOrCreate
$user = User::firstOrCreate(
['email' => 'john@example.com'],
['name' => 'John', 'password' => bcrypt('secret')]
);
// updateOrCreate
$post = Post::updateOrCreate(
['slug' => 'my-post'],
['title' => 'My Post', 'body' => 'Content...']
);
?>💡
Always define $fillable! Without it, mass assignment (like
Post::create($request->all())) won't work. This is a security feature to prevent unwanted fields from being saved.Test your knowledge!
Take a quiz to reinforce what you learned.