with manytomany relation between them. I want to create a form so user can add/edit a user. The form must be like
input elements to edit user details (email, password etc)
checkboxes to check roles
checkboxes to check permissions
My main issue is that I have to display all roles and check only the ones that user has permission. User::with("role") doesn't have because it filters only roles user has. So in order to get all roles and permissions I had to create 2 additional calls and use with to get all users with query (where)
It will get all roles and when a users relation is null then user hasn't the specific permission and when it has a record then it has the permission. Then in my gui I check this and check or not the specific checkbox.
It works but I feel it's not the proper way. Can you advice me what's the most laravel way?
You could just get only the user and mark the the checkboxes according to the related models' existence. Something like this.
$user = User::findOrFail();
// Is this user an admin?
$user->roles->keyBy('name')->has('admin'); // Assuming roles have a name field.
// Does this user have level 3 clearance?
$user->permissions->keyBy('name')->has('level 3 clearance'); // Assuming again, there's a name field.
You could do the keyBy in the controller if you want, as to not repeat the operation multiple times. And the code might be different depending on your model's structure. But you get the idea.