Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

webfuelcode's avatar

Select on roles, Trying to get property 'id'

I am working on laravel permission package and stuck on the user creation page for selecting the role.

Trying to get property 'id' of non-object

Controller

public function create()
    {
        $roles = Role::pluck('name','name')->all();
        return view('users.create',compact('roles'));
    }
<select name="role" id="" class="form-control" multiple>
                        <option value="">Select a role</option>
                        <option value="{{ $roles->id }}">{{ $roles->name }}</option>
                    </select>
0 likes
7 replies
automica's avatar

@webfuelcode you need to loop through your roles

<select name="role" id="" class="form-control" multiple>
    <option value="">Select a role</option>
    @foreach($roles as $role)
        <option value="{{ $role->id }}">{{ $role->name }}</option>
    @endforeach
</select>

EDIT: and change your controller method to what @michaloravec has posted below:

MichalOravec's avatar

Just retrieve all data

public function create()
{
    $roles = Role::all();

    // or $roles = Role::get(['id', 'name']);
    
    return view('users.create', compact('roles'));
}
jlrdw's avatar

Who is assigning the role. I hope in this case an administrator, otherwise a user can pick any role they want.

webfuelcode's avatar

@jlrdw thanks for the suggestion.

Actually, I am still learning laravel and this package. And this code is a part of a tutorial that I found on a blog for v6 and v7. I am using it on my laravel v7 so I am testing it.

Of course, user will not be able to assign roles...this page is only designed for admins only.

webfuelcode's avatar

@michaloravec @automica I am following a tutorial for laravel permission so I came to know about pluck. Would you please describe to me a little bit about it and where/when to use it?

MichalOravec's avatar

Working example with pluck.

public function create()
{
    $roles = Role::pluck('name', 'id');
    
    return view('users.create', compact('roles'));
}
@if ($roles->isNotEmpty())
    <select name="role" class="form-control" multiple>
        <option value>Select a role</option>
        
        @foreach($roles as $id => $name)
            <option value="{{ $id }}">
                {{ $name }}
            </option>
        @endforeach
    </select>
@endif

Docs: https://laravel.com/docs/8.x/collections#method-pluck

I think it is well explained in the examples in the documentation.

Please or to participate in this conversation.