【发布时间】:2020-03-29 07:15:24
【问题描述】:
请注意:我对 laravel 和一般编程很陌生。
所以我在“用户”和“角色”之间建立了多对多的关系,并使用我刚刚学习的数据透视表“role_user”这个新东西。现在我想显示我的用户列表和他们拥有的角色的名称。
用户迁移
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
角色迁移
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRolesTable extends Migration
{
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
});
}
public function down()
{
Schema::dropIfExists('roles');
}
}
role_user 迁移
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRoleUserTable extends Migration
{
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->bigInteger('role_id')->unsigned();
$table->bigInteger('user_id')->unsigned();
});
}
public function down()
{
Schema::dropIfExists('role_user');
}
}
用户模型
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password', 'roles_id'
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function authorizeRoles($roles)
{
if (is_array($roles)) {
return $this->hasAnyRole($roles) ||
abort(401, 'This action is unauthorized.');
}
return $this->hasRole($roles) ||
abort(401, 'This action is unauthorized.');
}
/**
* Check multiple roles
* @param array $roles
*/
public function hasAnyRole($roles)
{
return null !== $this->roles()->whereIn(‘name’, $roles)->first();
}
/**
* Check one role
* @param string $role
*/
public function hasRole($role)
{
return null !== $this->roles()->where(‘name’, $role)->first();
}
}
榜样
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public $timestamps = false;
public function users()
{
return $this->belongsToMany('App\User');
}
}
我的看法
@extends('layouts/app')
@section('content')
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4>Users</h4>
</div>
<div class="panel-body">
@if (count($users) > 0)
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Created on</th>
<th>Role</th>
</tr>
</thead>
@foreach ($users as $user)
<tr>
<td><em>{{$user->name}}</em></td>
<td><em>{{$user->email }} </em></td>
<td><em>{{$user->created_at}}</em></td>
<td><em>{{$user->roles->name}} </em></td>
<td>
<span class="table-remove">
{!!Form::open(['action' =>['userController@destroy', $user->id], 'method' => 'POST'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{ Form::button('<i class="fas fa-trash-alt" aria-hidden="true"></i>', ['class' => 'btn btn-danger btn-sm', 'type' => 'submit']) }}
{!!Form::close()!!}
</span>
</td>
</tr>
@endforeach
</table>
</div>
</div>
</div>
</div>
@else
<p>No users found</p>
@endif
用户控制器
class UserController extends Controller
{
public function index()
{
$users = User::all();
return view('users.index',['users'=> $users]);
}
}
现在我得到错误:
此集合实例上不存在属性 [名称]。 (查看:C:\xampp\htdocs\Laravel\AmbitieProject\resources\views\users\index.blade.php)
我尝试回显“$user->roles->name”,我认为它应该在一对多关系中起作用,但我不确定如何使用多对多关系回显角色名称
【问题讨论】:
-
你能分享你的控制器吗?
-
$user->roles将返回与用户关联的一个或多个角色的集合。然后,您需要在循环中获取每个角色,或者如果只有一个角色,请使用$user->roles->first()->name获取集合中的第一个条目:laravel.com/docs/5.8/collections#method-first -
$user->roles->first()->name 工作谢谢!
-
我作为答案添加了。
标签: laravel