K
K
knowledge2018-05-06 23:54:11
Laravel
knowledge, 2018-05-06 23:54:11

How to get relations from collections in laravel?

I get a collection of users
$users = User::whereIn('id', [1, 2, 3])->get();
The User model has a many-to-many relationship with the Role model
, is it possible to get the relationship values ​​directly from the collection, without iterating in a foreach loop?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniel, 2018-05-07
@knowledge

Relationships can be immediately loaded into the collection using Eager Loading . Next is the matter of technology. As an option to work with them by methods built into the collection.

$users = User::whereIn('id', [1, 2, 3])->with('roles')->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question