简体   繁体   中英

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM