Rename your function from roles to role,
public function role() {
then
User::with('role')->get();
@foreach($users as $user)
{{ $user->role->name }}
@endforeach
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi there, I'm trying to get simple user roles working. I just want every user to have a role, for example Visitor or Admin.
//User.php
public function roles()
{
return $this->hasOne(Role::class);
}
//Role.php
public function users()
{
return $this->belongsToMany(User::class);
}
//User table migration
$table->integer('role_id');
$table->foreign('role_id')->references('id')->on('roles');
I'm just trying to accoplish to get that relationship working, so that i can do this in the html:
@foreach($users as $user)
{{$user->role->name}}
@endforeach
Instead of doing:
@foreach($users as $user)
{{$user->role_id}}
@endforeach
Please or to participate in this conversation.