Frnak
Frnak

Reputation: 6812

Laravel Eloquent best practice reading entries including relationships

I have a Model called "Services" and another called "Licenses". A Service has many licenses and a licenses belongs to one service.

When I want to return all services including their licenses I currently do the following

$services = Auth::user()->services;
foreach($services as $service) {
    $service->licenses;
}

This is working, but I'd love to have something cleaner since I use this very often and sometimes in very deep structures.

Upvotes: 1

Views: 82

Answers (1)

patricus
patricus

Reputation: 62398

If you're just trying to load all the related records, you can do so using eager loading or lazy eager loading, both of which accept nested relationships.

In your example, since you already have the User loaded, you can use the load() method to lazy eager load the related records:

Auth::user()->load('services.licenses');
dd(Auth::user());

Regular eager loading works the same way:

$user = User::with('services.licenses')->find(Auth::user()->id);
dd($user);

Upvotes: 1

Related Questions