Relationships
Relationships describe model associations.
What it is
Relationships describe model associations.
When to use it
Use belongsTo/hasMany for ownership and eager loading to avoid N+1 queries.
Syntax
public function user(): BelongsTo { return $this->belongsTo(User::class); }Example
// In Order:
use Illuminate\Database\Eloquent\Relations\BelongsTo;
public function user(): BelongsTo { return $this->belongsTo(User::class); }
// In User:
use Illuminate\Database\Eloquent\Relations\HasMany;
public function orders(): HasMany { return $this->hasMany(Order::class); }
// Query:
$orders = Order::with("user")->paginate(20);Common mistakes
Wrong foreign keys silently break associations; eager loading does not remove authorization needs.