Y
Y
Yuri Voronin2019-04-03 12:01:42
Laravel
Yuri Voronin, 2019-04-03 12:01:42

Where is the error in the table connection?

Hello. I make a connection between tables (many-to-many)
There is a table user , roles , role_user
role_user:

Schema::create('role_user', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    $table->integer('role_id')->unsigned();
    $table->foreign('role_id')->references('id')->on('roles');
    $table->timestamps();
});

5ca474985682d151802478.pngIn the User model:
public function roles()
{
    return $this->belongsToMany('App\Role');
}

In one of the controllers I'm trying to do (most likely I'm not getting the name of the role correctly):
$roles = User::where('id', '1')->first()->roles();
foreach ($roles as $role) {
    echo $role->name;
}

dd($roles) returns
5ca475fd6fff4597075524.png
How do I get the role name?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Crash XD, 2019-04-03
@yuraSco

$roles = User::where('id', '1')->first()->roles();

So you just get the request.
To get the final result, either add at the end ...->get()or call ->roles right away:
$roles = User::where('id', '1')->first()->roles()->get();
$roles = User::where('id', '1')->first()->roles;
In both cases, $roles will store a collection of roles, not just a query.

J
jazzus, 2019-04-03
@jazzus

Write correctly. In the User model

public function roles() {
   return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
}

In the controller
// Роли авторизованного пользователя
$roles = Auth::user()->roles()->get();
// Роли любого пользователя по id
$id = 5;
$roles = User::find($id)->roles()->get();
// Все юзеры с их ролями и количеством ролей 
$users = User::with('roles')
             ->withCount('roles')
             ->get();

In template
//роли юзера
@foreach ($roles as $role)
  {{ $role->name }}
@endforeach
// Роли у всех юзеров
@foreach ($users as $user)
        //количество ролей у юзера
        {{$user->roles_count}}
        //названия ролей у каждого юзера
        @foreach ($user->roles as $role)
          {{ $role->name }}
        @endforeach
 @endforeach

Adding an admin constant to the Role model In the controller
// Сделать юзера админом
$user->roles()->attach(Role::ID__ADMIN);
// админы
$admins = Role::find(Role::ID__ADMIN)->users()->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question