how do I hide some attributes from the model in just some routes, for example:
I'm using protected $hidden to hide elements but this hide in all my functions or restful routes (index, show)
 $hidden = [
  'coachVisibility', 'thumbnail', 'studentVisibility',
  'isHTML', 'studentIndex', 'coachIndex',
  'isURL', 'source', 'path',
  'status', 'updateTime', 'isfolder',
  'parentResource', 'idModifierUser', 'idResourceType',
  'idCreatorUser', 'idCreationCountry', 'user',
  'country', 'resource'
];
I want to hide only in Index function but in show function I don't want to hide anything.
You can use the addHidden method on the models:
class UsersController
{
    public function index ()
    {
        return User::all()->each(function ($user) {
            $user->addHidden([.........]);
        });
    }
}
Once this PR gets merged, you'll be able to call it directly on the collection:
class UsersController
{
    public function index ()
    {
        return User::all()->makeHidden([.........]);
    }
}
According to your comment, you can keep all of those fields in the $hidden property of your model, and instead make them visible only in the show method:
public function show($id)
{
    return CTL_Resource::where('idResource', $id)
        ->with('tags', 'quickTags', 'relatedTo')
        ->firstOrFail()->makeVisible([
            'coachVisibility', 'thumbnail', 'studentVisibility'
        ]);
}
                        Consider using Transformers to transform return data as you would like.
For eg:
Create an abstract Transformer:
namespace App\Transformers;
abstract class Transformer
{
    public function transformCollection(array $items)
    {
        return array_map([$this, 'transform'], $items);
    }
    public abstract function transform($item);
}
Then create custom transformers for each method if you like:
namespace App\Transformers;
use App\User;
class UserTransformer extends Transformer {
    public function transform($user) {
         return [
             'custom_field' => $user['foo'],
             'another_custom_field' => $user['bar']
             ...
        ];
    }
}
Then in your controller:
...
public function index(Request $request, UserTransformer $transformer)
{
    $users = User::all();
    return response()->json([
        'users' => $transformer->transformCollection($users->toArray())
     ], 200);
}
There are a couple of advantages to this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With