behzad m salehi
behzad m salehi

Reputation: 1076

Retrive Roles name for collection of users in laravel

i want to pass users role to blade .

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() ;
    });

errors i get :

ErrorException in UsersController.php line 23: Undefined property: Illuminate\Database\Eloquent\Collection::$name

whats wrong with the "name" i trying to get ?


ps : when i change :

           echo ( !$user->roles->isEmpty() ? $user->roles->name : 'No Role' ); 

to :

           echo ( !$user->roles->isEmpty() ? $user->roles : 'No Role' );

this results will shown:

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

Upvotes: 1

Views: 734

Answers (2)

behzad m salehi
behzad m salehi

Reputation: 1076

i find the solution by myself :

i must use :

 user->roles->first()->name

instead of :

user->roles->->name

cause "user->roles" return a collection and i must use collection method before trying to get object properties

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

You're checking if roles is empty and if it is, you're trying to get property. So, change code to this:

$user->roles->isEmpty() ? 'No Role' : $user->roles->name

Upvotes: 0

Related Questions