Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Hide attributes from model just in some routes

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.

like image 377
CanKer Avatar asked Apr 14 '16 01:04

CanKer


2 Answers

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'
        ]);
}
like image 75
Joseph Silber Avatar answered Nov 14 '22 14:11

Joseph Silber


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:

  1. You can show/hide data as you wish with specific transformers
  2. In-case you decide to change the column names in your table, your transformers will ensure that clients getting your data will not break.
like image 44
Angad Dubey Avatar answered Nov 14 '22 15:11

Angad Dubey