Issue
In a controller, I use this code to get all Text
objects and their associated authors
return Text::with('authors')->get();
This is part of a backend only available to admins, and I need them to be able to access the authors name
fields. But in the Author
model, I set protected $hidden = ['name'];
when I programmed another part of my app that's for standard users.
There's a hasMany
relationship: Each text has many authors. Is there a way to use with
, but get some hidden attribute? Or the other way round, to declare some attribute as hidden temporarily when using with
?
Please note this is question is about the use of with
in combination with hidden attributes. I'm not looking for something like $authors = $authors->makeVisible(['name']);
(which is explained here).
Solution
I could find two approaches to solve my problem:
1) Using each
as seen in this question
$texts = Text::with('authors')
->get()
->each(function ($text) {
$text->authors->makeVisible(['name']);
});
2) Using transform()
as recommended in an answer to the same question. This seems to be way faster.
$texts = Text::with('authors')
->get()
->transform(function ($text) {
$text->authors->makeVisible(['name']);
return $text;
});
Answered By - Pida
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.