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

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners