Answer the question
In order to leave comments, you need to log in
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();
});
public function roles()
{
return $this->belongsToMany('App\Role');
}
$roles = User::where('id', '1')->first()->roles();
foreach ($roles as $role) {
echo $role->name;
}
Answer the question
In order to leave comments, you need to log in
$roles = User::where('id', '1')->first()->roles();
...->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.
Write correctly. In the User model
public function roles() {
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
}
// Роли авторизованного пользователя
$roles = Auth::user()->roles()->get();
// Роли любого пользователя по id
$id = 5;
$roles = User::find($id)->roles()->get();
// Все юзеры с их ролями и количеством ролей
$users = User::with('roles')
->withCount('roles')
->get();
//роли юзера
@foreach ($roles as $role)
{{ $role->name }}
@endforeach
// Роли у всех юзеров
@foreach ($users as $user)
//количество ролей у юзера
{{$user->roles_count}}
//названия ролей у каждого юзера
@foreach ($user->roles as $role)
{{ $role->name }}
@endforeach
@endforeach
// Сделать юзера админом
$user->roles()->attach(Role::ID__ADMIN);
// админы
$admins = Role::find(Role::ID__ADMIN)->users()->get();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question