1

I'm using lumen to develop a REST API. I used for that 2 models User and Post. In my User model I can get all the user's posts using the hasMany() method:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
  // ...
  public function posts()
  {
    return $this->hasMany('App\Post');
  }
  // ...

It's really helpfull to get all my user posts:

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

Problem is that the Post model has some hidden attributes that are not shown in the response (which is the normal behaviour) but for some request I need to return them. For this purpose, laravel provide a method called makeVisible(). So I decide to used it in my posts() method:

  public function posts()
  {
    return $this->hasMany('App\Post')->makeVisible(['hiddenAttribute', ...]);
  }

But unfortunately things aren't as simple as that and I get this error:

Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::makeVisible()

Has anyone an idea how I can use this both methods together?

johannchopin
  • 13,720
  • 10
  • 55
  • 101
  • 1
    Something like this. `User::find($id)->posts ->transform(function ($post) { $post->makeVisible(['hiddenAttr']); return $post; });` – porloscerros Ψ May 05 '20 at 21:10

1 Answers1

1

option 1:

like porloscerros Ψ said in comment, you have to iterate over all your model collection and make visible

$value = User::find($id)->posts->each(function ($post, $key))
  {
    $post->makeVisible(['hiddenAttribute',...]);
  }
); 

return response()->json($value, 200);

option 2: extend model class to fit your need... see: https://stackoverflow.com/a/44169024/10573560

johannchopin
  • 13,720
  • 10
  • 55
  • 101
OMR
  • 11,736
  • 5
  • 20
  • 35