I think in_array() works just fine for this situation, but you could also use isset() as well. For that you would do something like:
{{ isset($userroles[$role->id]) ? "checked" : "" }}
If you'd like a more "Laravel" way of doing it, you could also use the array helper array_has() helper function provided by Laravel. Using this function, you would do something like this:
{{ array_has($userroles, $role->id) ? "checked" : "" }}
I personally prefer to do this kind of logic with a function on the User model. Below is some code that I would put on the User model and then the blade to accomplish this:
User Model
/**
* Determine if the user has the given role.
*
* @param mixed $role
* @return boolean
*/
public function hasRole($role)
{
// Assuming your role model has a 'name' field on it
if (is_string($role)) {
return $this->roles->contains('name', $role);
}
// If you pass a role id in, check by id
if (is_numeric($role)) {
return $this->roles->contains('id', $role);
}
// If you pass a Role object in, compare each of your role's id to this one's
foreach ($this->roles as $user_role) {
if ($user_role->id == $role->id) {
return true;
}
}
// If nothing matched, return false
return false;
}
Then in the blade do this:
{{ $user->hasRole($role->id) ? "checked" : "" }}
To avoid the @php block, you could move that query to your controller and pass it down to the blade.
// This code should be in whatever function is directing Laravel to show your blade.
$user = 'your user query';
$roles = 'your roles query';
$userroles = $user->roles->pluck('id')->toArray();
return view('your.view.name', compact('user', 'roles', 'userroles'));