How To Hide Attributes From JSON In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

When building JSON APIs, you will often need to convert your models and relationships to arrays or JSON. Eloquent includes convenient methods for making these conversions, as well as controlling which attributes are included in your serializations and when you want to hide certain data like password and remember_token we can also done that in laravel

How To Hide Attributes From JSON In Laravel With Example

Hiding Attributes From JSON

Sometimes you may wish to limit the attributes, such as passwords, that are included in your model's array or JSON representation.

To do so, add a $hidden property to your model:

Example(1)

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}


When hiding relationships, use the relationship's method name.

Alternatively, you may use the visible property to define a white-list of attributes that should be included in your model's array and JSON representation.


All other attributes will be hidden when the model is converted to an array or JSON:

Example(2)

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be visible in arrays.
     *
     * @var array
     */
    protected $visible = ['first_name', 'last_name'];
}
 

Temporarily Modifying Attribute Visibility

If you would like to make some typically hidden attributes visible on a given model instance, you may use the makeVisible method. The makeVisible method returns the model instance for convenient method chaining:

<?php

namespace App\Http\Controllers;
use App\Http\Requests;

use App\User;

class demoController extends AppBaseController
{
    public function index()
    {
        $user = User::find(1);

        return $user->makeVisible('attribute')->toArray();
    }
}


Likewise, if you would like to make some typically visible attributes hidden on a given model instance, you may use the makeHidden method.

<?php

namespace App\Http\Controllers;
use App\Http\Requests;
use App\User;

class demoController extends AppBaseController
{
    public function SerializationToJSON()
    {
        $user = User::find(1);

        return $user->makeHidden('attribute')->toArray();
    }
}

Related Post