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

fcno's avatar
Level 6

Roles Permissions (n:m) bring all with extra propertie

Current scenario:

I have the role and I eagerly load your permissions.

protected function edit(Role $role)
{
	$role->load(['permissions' => function($query) {
        $query->select('id');
    }]);

	$permissions = Permission::get();

	return view ('someview', compact('role', 'permissions'));
}

With this, in the edit view I can display which permissions are linked to the role and which are not. Visually, this translates to a checkbox that will or will not be checked.

// view.blade.php

@foreach($permissions as $permission )
    ...
    @checked(($role->permissions->contains($permission->id))

@endforeach

Would it be possible to transform the two queries above into one (load and get permissions)?

I thought of something like this (pseudo code):

protected function edit(Role $role)
{
	$permissions = Permission::takeThemAllButSayWhichOnesAreRelatedToTheRole($role->id);

	return view ('someview', compact('role',  'permissions'));
}

So in the view I could do the following, imagining that the query brings the 'checked' property directly from the database.

@foreach($permissions as $permission )
    ...
    @checked(($permission->checked)

@endforeach

I don't know if this is the best strategy, nor do I know if it is possible, because I have my limitations in 'thinking sql'. But I would like an answer as to whether or not I should go that approach.

Thanks for the help.

0 likes
1 reply
kevinbui's avatar
kevinbui
Best Answer
Level 41

Your solution is the best. Just a small suggestion from myself. To me, this is a bit cleaner but slower.

protected function edit(Role $role)
{
	$role->load('permissions');

	$permissions = Permission::get();

	return view ('someview', compact('role', 'permissions'));
}

@foreach($permissions as $permission )
    @checked(($role->permissions->contains($permission))
@endforeach

Please or to participate in this conversation.