Eloquent Models
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Post extends Model
{
protected $fillable = ["title", "body", "user_id"];
protected function casts(): array
{
return [
"published_at" => "datetime",
"is_published" => "boolean",
"metadata" => "array",
];
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
}Relationship Types
// One to One
public function profile(): HasOne {
return $this->hasOne(Profile::class);
}
// One to Many
public function posts(): HasMany {
return $this->hasMany(Post::class);
}
// Many to Many
public function roles(): BelongsToMany {
return $this->belongsToMany(Role::class)
->withPivot("assigned_at")
->withTimestamps();
}
// Has Many Through
public function comments(): HasManyThrough {
return $this->hasManyThrough(Comment::class, Post::class);
}
// Polymorphic
public function images(): MorphMany {
return $this->morphMany(Image::class, "imageable");
}Eager Loading
// Prevent N+1
$posts = Post::with("user", "comments")->get();
// Nested eager loading
$posts = Post::with("comments.user")->get();
// Lazy eager loading
$posts = Post::get();
$posts->load("user");
// Default eager loading on model
protected $with = ["user"];Laravel 13: Model Improvements
Laravel 13 introduces #[Fillable] and #[Appends] attributes replacing $fillable and $appends properties for declarative configuration directly on the model class.