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

Shivamyadav's avatar

How to get a select option getting the data from the database table?

I want to get the id and the name into the select tag , as I have used it in the controller using pluck method.

My controller code

  public function create()
    {
        $roles =Role::pluck('name','id',)->all();
        return view('admin.users.create', compact('roles'));
    }

My blade file code

<div class="mb-6">
            <label for="Role" class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300">Role</label>
            <select type="text" name="role_id" id="role_id">
                {{ $roles->id}}
            </select>
        </div>
0 likes
10 replies
Sinnbeck's avatar

Dont add ->all() as that will convert it to an array. But getting it like this might be better

$roles =Role::get(['name','id']);

And you need to specify the options

<select type="text" name="role_id" id="role_id">
   @foreach($roles as $role)
   <option value="{{$role->id}}">{{$role->name}}</option>
   @endforeach
</select>
1 like
Shivamyadav's avatar

@Sinnbeck i don't understand . Using all method it will get an array ,after removing the all method why should i am unable to access it , whithout using foreach loop.🤦‍♂️

Sinnbeck's avatar

@Shivamyadav Because you are getting every single role from the database as a collection (or nested array). So you need to have a foreach to show all the items.

1 like
Shivamyadav's avatar

@Sinnbeck thanks for clarifying doubts sir 🙏.. i have done the changes and it shows this error

Attempt to read property "id" on string
Sinnbeck's avatar

@Shivamyadav Can you show your controller method again after the changes, and check if you use $roles anywhere in your blade file ?

1 like
Shivamyadav's avatar

@Sinnbeck Controller code

 public function create()
    {
        $roles = Role::pluck('name', 'id');
        return view('admin.users.create', compact('roles'));
    }

my blade code , $roles is used in only foreach loop

@foreach($roles as $role)
                <option value="{{ $role->id}}">{{$role->name}}</option>
                @endforeach
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@Shivamyadav So I see you are still using pluck() even though I suggested get()

If you want to use pluck() you need this blade code

<select type="text" name="role_id" id="role_id">
   @foreach($roles as $id => $role)
   <option value="{{$id}}">{{$role}}</option>
   @endforeach
</select>
1 like

Please or to participate in this conversation.