Search code examples
phplaravellumen

Laravel: Use makeVisible() after a hasMany() call


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?


Solution

  • 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