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

janmoes's avatar

User Roles

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
0 likes
4 replies
Sergiu17's avatar

Rename your function from roles to role,

public function role() {

then

User::with('role')->get();
@foreach($users as $user)
	{{ $user->role->name }}
@endforeach
janmoes's avatar

I did that yeah. But than i get this error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.user_id' in 'where clause' (SQL: select * from `roles` where `roles`.`user_id` in (1))

janmoes's avatar

Okay, so i had to change hasOne into belongsTo, otherwise they expect a user_id in the roles table. But now i get this error Trying to get property 'name' of non-object (View: D:\wamp64\www\webprepare_dashboard\resources\views\users\index.blade.php) which comes from the $user->role->name

janmoes's avatar

Alright got it working! Appearently my role_id was 0 while the admin rank(first rank) in the table has a value of 1 because database tables start incrementing at 1 instead of 0 like an array

1 like

Please or to participate in this conversation.