检索角色名称以收集laravel中的用户 [英] Retrive Roles name for collection of users in laravel
本文介绍了检索角色名称以收集laravel中的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将用户角色传递给blade.
i want to pass users role to blade .
Usercontroller:
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:
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
ErrorException in UsersController.php line 23: Undefined property: Illuminate\Database\Eloquent\Collection::$name
我试图获取的名称"有什么问题?
whats wrong with the "name" i trying to get ?
ps:当我更改时:
echo ( !$user->roles->isEmpty() ? $user->roles->name : 'No Role' );
至:
echo ( !$user->roles->isEmpty() ? $user->roles : 'No Role' );
此结果将显示:
无角色
[{"id":11,名称":用户",标签":可以拥有许可证的标准用户","created_at":"2016-09-0518:36:53," updated_at:" 2016-09-05 18:36:53,"数据透视:{" user_id:103," role_id:11}}]]
没有角色
无角色
[{"id":8,名称":"FinancialAndOfficial Manager","lable":能够管理财务公司","created_at":"2016-09-05 18:36:53","Updated_at:" 2016-09-05 18:36:53,"数据透视:{" user_id:106," role_id:8}}]]
无作用
[{" id:4,名称":"QalityControl Manager",标签":能够管理QalityCon的公司","created_at":"2016-09-05 18:36:53","updated_at":"2016-09-05 18:36:53,"数据透视:{" user_id:108," role_id:4}}}]
[{" id:11," name:" User," lable":可以具有许可证资产的标准用户","created_at":"2016-09-05 18:36:53","updated_at":"2016-09-05 18:36:53",数据透视":{"user_id":109,"role_id":11}}]]
没有角色
没有角色
No Role
[{"id":11,"name":"User","lable":"A standard user that can have a licence assig","created_at":"2016-09-05 18:36:53","updated_at":"2016-09-05 18:36:53","pivot":{"user_id":103,"role_id":11}}]
No Role
No Role
[{"id":8,"name":"FinancialAndOfficial Manager","lable":"Able to manage the company that the Financial","created_at":"2016-09-05 18:36:53","updated_at":"2016-09-05 18:36:53","pivot":{"user_id":106,"role_id":8}}]
No Role
[{"id":4,"name":"QalityControl Manager","lable":"Able to manage the company that the QalityCon","created_at":"2016-09-05 18:36:53","updated_at":"2016-09-05 18:36:53","pivot":{"user_id":108,"role_id":4}}]
[{"id":11,"name":"User","lable":"A standard user that can have a licence assig","created_at":"2016-09-05 18:36:53","updated_at":"2016-09-05 18:36:53","pivot":{"user_id":109,"role_id":11}}]
No Role
No Role
但是我只是尝试从上面的行中获取名称"
but i just try to fetch 'name' from above rows
推荐答案
我自己找到解决方案:
我必须使用:
user->roles->first()->name
而不是:
user->roles->->name
由于用户->角色"返回一个集合,因此在尝试获取对象属性之前,我必须使用集合方法
cause "user->roles" return a collection and i must use collection method before trying to get object properties
这篇关于检索角色名称以收集laravel中的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文