Andreas Hunter
Andreas Hunter

Reputation: 5024

How I can hide with better way laravel model fields

I hide my eloquent fields something like this in my case:

public function __construct(array $attributes = array())
{
    parent::__construct($attributes);
    $user = auth()->user();
    $hiddenFields = [];
    if(!$user || $user && $user->id !== $this->user_id) {
        $hiddenFields = [
            'phone', 'employees', 'email',
            'created_at', 'updated_at', 'id', 'description'
        ];
    }
    $this->hidden = array_merge($this->hidden, $hiddenFields);
}

Can be hide field better?

Upvotes: 2

Views: 1165

Answers (2)

zoider23
zoider23

Reputation: 61

The user call in the constructor will always see null as required middleware has not yet ran, see https://stackoverflow.com/a/39175335/11995193. Note this assumes you've posted code from a controller.

For the rest of the class I'd personally add aminor refactor to make the code more readable:

class SomeClassName
{
    /**
     * @var array
     */
    protected $defaultHiddenFields = [
        'phone',
        'employees',
        'email',
        'created_at',
        'updated_at',
        'id',
        'description'
    ];

    /**
     * @var array
     */
    protected $hidden = [];

    /**
     * @param  array  $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->middleware(function ($request, $next) {
            $this->user = auth()->user();

            return $next($request);
        });

        $this->hidden = array_merge($this->hidden, $this->getHiddenUserFields());
    }

    /**
     * @return array
     */
    private function getHiddenUserFields(): array
    {
        $validUser = !$this->user || ($this->user && ($this->user->id !== $this->user_id));

        return $validUser ? $this->defaultHiddenFields : [];
    }
}

Upvotes: 1

Jorge Rodríguez
Jorge Rodríguez

Reputation: 176

You could either use $visible or $hidden in the model directly so when performing calls to ->toArray() they won't be displayed.

Documentation: https://laravel.com/docs/master/eloquent-serialization#hiding-attributes-from-json

Upvotes: 1

Related Questions