In addition to the response from @DiegoSouza , you can do this using with
using the relationship name as chave
and Closure
as value.
See:
$with['role'] = function ($query) {
$query->select('id', 'name');
};
User::with($with)->get();
Note that in the question you were prompted to select only the name
field of Role
, however Laravel does the data relationship internally using the value defined in Model::getKey()
(in this case id
) of Role
.
So, whenever you were to select
in a relationship, you need to select the fields where Laravel will assign the values.
A second example:
$with['role'] = function ($query) {
$query->select('id', 'name');
};
User::select('name', 'role_id')->with($with)->get();
In this second example, I would also need to select role_id
, if I were to choose the fields of User
, since internally Laravel would relate User::$role_id
to Role::$id
;