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>
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>
@Sinnbeck and how should i get it in the blade file .
both name and id
@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.🤦♂️
@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.
@Sinnbeck thanks for clarifying doubts sir 🙏..
i have done the changes and it shows this error
Attempt to read property "id" on string
@Shivamyadav Can you show your controller method again after the changes, and check if you use $roles anywhere in your blade file ?
@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
@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>
Please sign in or create an account to participate in this conversation.