1

I have in my User model a posts() method that return me all the Post. It's enable me to get really easily all posts in a json:

return response()->json(User::find($id)->posts()->get(), 200);

The method is written like that:

public function posts()
{
  $posts= $this->hasMany('App\Post');
  return $posts;
}

Problem is that I want to makeVisible some attributes of all my posts. So I use the each() method just like that:

public function posts()
{
  $posts= $this->hasMany('App\Post');

  $posts->each(
    function ($post, $key) {
      $post->makeVisible(['hiddenAttribute', ...]);
    }
  );

  return $posts;
}

But I don't see any changes in my response. Did I miss something?

johannchopin
  • 13,720
  • 10
  • 55
  • 101
  • Does this answer your question? [Laravel - how to makeVisible an attribute in a Laravel relation?](https://stackoverflow.com/questions/44167733/laravel-how-to-makevisible-an-attribute-in-a-laravel-relation) – Remul May 07 '20 at 15:25
  • 1
    The posts() method in your user model is just to define the relationship for making queries to DB. Do the `each` in the controller after having made the query, that is, on the collection that returns the query – porloscerros Ψ May 07 '20 at 15:32
  • @porloscerrosΨ You really saved my life this time thank you so much. You are right the `each` has to be done on the `return` of the `posts` method. You can write it in a answer and I will `validate` it ;) – johannchopin May 07 '20 at 15:49
  • @Remul I think you are wrong calling this a duplicate. The response that you ping show how to use `makeVisible` in different situation and his really hard to get the infos out of it. I already upvoted this answer before but I didn't see the subtility to use `makeVisible` after that the function is called. Response of this question will be more specific – johannchopin May 07 '20 at 15:53

0 Answers0