Home > Net >  In laravel, How to display role name by role_id in user listing?
In laravel, How to display role name by role_id in user listing?

Time:09-22

USER MODEL

public function roles()
{
    return $this->belongsTo(User::class, 'roles');
}

ROLE MODEL

public function users()
{
    return $this->hasMany(Role::class, 'role_id');
}

BLADE FILE

<tbody>
@foreach($users as $user)
    <tr>
        <td>{{$user->name}}</td>
        <td>{{$user->email}}</td>
        <td>{{$user->country}}</td>
        <td>{{$user->state}}</td>
        <td>{{$user->city}}</td>
        <td>{{$user->role_id}}</td>
        <td>
            <button><a href="{{route('edituser', $user->id)}}">EDIT</a></button>
        </td>
        <td>
            <button class="deleteuser" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}">DELETE</button>
        </td>
    </tr>
@endforeach
</tbody>

role_id is foreign key in users table. please help me how to display role name while displaying users list.

CodePudding user response:

You have reverse the way you define relationship between User and Role model it should be like this

class User extends Model {
    public function role() {
        return $this->belongsTo(Role::class);
    }
}

class Role extends Model {
    public function users() {
        return $this->hasMany(User::class);
    }
}

With this kind of definition on the user model you should have define a role_id in the create_users_table migration.

and to display the role name you can perform it like this

@foreach($users as $user)
    <tr>
        {{-- other code goes here --}}

        <td>{{ $user->role->name }}</td>
        
        {{-- other code goes here --}}
    </tr>
@endforeach

This presume a user can only have one single role

CodePudding user response:

Try these changes in your code. I hope it will work

USER MODEL

public function role(){
        return $this->belongsTo(Role::class,'role_id');
    }

ROLE MODEL

public function users(){
        return $this->hasMany(User::class, 'role_id');
    }

User Controller

public function index(){

        $users = User::with('role')->get();
        return $users;
    }

BLADE FILE

<tbody>
   @foreach($users as $user)
      <tr>
          <td>{{$user->name}}</td>
          <td>{{$user->email}}</td>
          <td>{{$user->country}}</td>
          <td>{{$user->state}}</td>
          <td>{{$user->city}}</td>
          <td>{{$user->role->name}}</td>
          <td><button><a href="{{route('edituser', $user->id)}}">EDIT</a> 
          </button></td>
          <td><button class="deleteuser" data-id="{{ $user->id }}" data-token=" 
          {{ csrf_token() }}" >DELETE</button></td>
        </tr>
      @endforeach
  </tbody>
  • Related