Source: paulund.co.uk

Laravel Eager Load Constraints
In a recent project I had to add a constraint to a relationship to make sure it only loads one of a relationship data. In the documentation it shows how you will use a one-to-many relationship by defining a $this->hasMany() relationship. Therefore if you have an application with a user where you keep track of all their activities you may have a model like this.

$user = User::with('activities')->find(1); This will return the user object with a relationship node of all the activities connected to this user.

class User extends Authenticatable { public function activities() { return $this->hasMany('App\Activities'); } public function lastActivitiy() { return $this->hasOne('App\Activities')->orderBy('created_at', 'DESC'); }}
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