Source: martinjoo.dev

Blog for Laravel Artisans
This article is all about Laravel Eloquent. We love it, we use it, but there are a lot of hidden gems!

Before Laravel 8.x we wrote attribute accessors and mutators like these: class User extends Model { public function getNameAttribute(string $value): string { return Str::upper($value); } public function setNameAttribute(string $value): string { $this->attributes['name'] = Str::lower($value); }}

This is a simple hasMany relationship: class Department extends Model { public function employees(): HasMany { return $this->hasMany(Employee::class); }} class Employee extends Model { public function paychecks(): HasMany { return $this->hasMany(Paycheck::class); }} If we need all the paychecks within a department we can write: $department->employees->paychecks; Instead of this, you can define a paychecks relationship on the Department model with the hasManyThrough: class Department extends Model { public function employees(): HasMany { return $this->hasMany(Employee::class); } public function paychecks(): HasManyThrough { return $this->hasManyThrough(Paycheck::class, Employee::class); }}
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners