我想将用户角色传递给刀片。
Usercontroller:
public function index(){
$users = User::with('roles')->paginate(10);
foreach ($users as $user ) {
echo ( !$user->roles->isEmpty() ? $user->roles->name : 'No Role' );
}
}
Create_role_table_migration:
Schema::create('roles', function (Blueprint $table) {
$table->increments('id')->unique();
$table->string('name', 45);
$table->string('lable', 45);
$table->timestamps() ;
});
我得到的错误:
UsersController.php第23行中的ErrorException: 未定义属性:Illuminate \ Database \ Eloquent \ Collection :: $ name
"名称"是什么?我试着去?
ps:当我改变时:
echo ( !$user->roles->isEmpty() ? $user->roles->name : 'No Role' );
到:
echo ( !$user->roles->isEmpty() ? $user->roles : 'No Role' );
此结果将显示:
没有角色
[{" id":11," name":" User"," lable&# 34;:"可以拥有许可证分配的标准用户",#34; created_at":" 2016-09-05 18:36:53",&#34 ; updated_at":" 2016-09-05 18:36:53"," pivot":{" user_id":103," role_id& #34;:11}}]
无角色
无角色
[{" id":8," name":" FinancialAndOfficial Manager"," lable":"能够管理公司财务"," created_at":" 2016-09-05 18:36:53"," updated_at":" 2016-09 -05 18:36:53"," pivot":{" user_id":106," role_id":8}}]
否角色
[{" id":4," name":" QalityControl Manager"," lable":"能够管理QalityCon"," created_at":" 2016-09-05 18:36:53"," updated_at":&# 34; 2016-09-05 18:36:53"," pivot":{" user_id":108," role_id":4}}]
[{&#34; id&#34;:11,&#34; name&#34;:&#34; User&#34;,&#34; lable&#34;:&#34; A标准可以拥有许可证分配的用户&#34;,&#34; created_at&#34;:&#34; 2016-09-05 18:36:53&#34;,&#34; updated_at&#34;:&#34 ; 2016-09-05 18:36:53&#34;,&#34; pivot&#34;:{&#34; user_id&#34;:109,&#34; role_id&#34;:11}}] < hr />无角色
无角色
但我只想尝试取名&#39;从上面的行
答案 0 :(得分:0)
您正在检查roles
是否为空,如果是,则您正在尝试获取财产。所以,将代码更改为:
$user->roles->isEmpty() ? 'No Role' : $user->roles->name
答案 1 :(得分:0)
我自己找到解决方案:
我必须使用:
user->roles->first()->name
而不是:
user->roles->->name
原因&#34;用户 - &gt;角色&#34;返回一个集合,我必须在尝试获取对象属性之前使用集合方法