Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

calin.ionut's avatar

make hidden all fields except the specified

I have this query and want to hide all the fields except title (I don't wan to use in the model protected hidden.....)

$roles = Role::with('permissions')
    ->paginate()
    ->through(fn($role) => [
        'id' => $role->id.
       'title' => $role->title,
       'permissions' => $role['permissions']->makeVisible(['title']) // <== here
]);

I know about makeHidden ..... but I have to declare all the fields.

I want to hide all except title.

How can I do that in laravel 8 ?

0 likes
10 replies
calin.ionut's avatar

I found it

'permissions' => $role['permissions']->map(function($permission) {
    return $permission->title;
})
tykus's avatar

@calin.ionut you can use a higher order function like I have shown since you only need one property from the Permission instance:

'permissions' => $role['permissions']->map->title 
tykus's avatar
tykus
Best Answer
Level 104

Either select only the columns you want/need:

Role::with('permissions:title,role_id')
    ->paginate()
    ->through(fn($role) => [
        'id' => $role->id.
       'title' => $role->title,
       'permissions' => $role['permissions']
]);

or, map over the Collection of permissions

Role::with('permissions')
    ->paginate()
    ->through(fn($role) => [
        'id' => $role->id.
       'title' => $role->title,
       'permissions' => $role['permissions']->map->title 
]);
1 like
tykus's avatar

@calin.ionut just remember you do need the foreign key otherwise Eloquent cannot put the Permission with its associated Role.

calin.ionut's avatar

@tykus there is many - many between roles - permission (pivot table permission_role)

calin.ionut's avatar

@tykus one thing..... using with('permissions:title') also return the pivot table. How to hide it ?

Please or to participate in this conversation.