seoppc
seoppc

Reputation: 2824

Hide relationship on Laravel Eloquent query

I need your suggestion about better way to hide information from relationship array.

$members = User::with('profile')->paginate(9);

$members->makeHidden([
    'slug', 'profile.avatar'
]);

dd($members->toArray());

This code doesn't hide information from profile array.

Thanks

Upvotes: 2

Views: 3280

Answers (2)

Ohgodwhy
Ohgodwhy

Reputation: 50798

makeHidden isn't supported for relationship properties, only the entire relationship. Instead, take what you want:

$member = User::with(['profile' => $function($query) {
    $query->select('id', 'user_id', 'about');
}])->paginate(9);

The above would only give you the id, user_id, and about fields explicitly, for example.

Edit

If you're using 5.6 you can define the columns as a comma separated string, too:

$member = User:with('profile:id,user_id,about')->paginate(9);

Upvotes: 4

ATechGuy
ATechGuy

Reputation: 1270

Add them to your model itself.

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

<?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'];
}

This will fix you up

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

Upvotes: 2

Related Questions