Eden WebStudio Eden WebStudio - 2 months ago 10
MySQL Question

Laravel render dropdown list from related table under employee table

I have 2 tables. Employee table and Roles tables. In my employee.show blade I want to render the dropdown list of the role already assgined or available to assign. I am not using collective forms and am a little stuck as all tutorials use thse.

My controller

public function show($employee)
$employee = Employees::find($employee);
$roles = Roles::pluck('role_name', 'id');
return view('employees.show')->withEmployee($employee)->withRoles($roles);

and my show.blade. Question is how do i pull the complete list from db of all other roles so a user can update?

<div class="form-group">
<label class="col-md-4 control-label" for="roles_id">Role</label>
<div class="col-md-4">
<select id="roles_id" name="roles_id" class="form-control">
<option value="{{ $employee->roles->id }}">{{ $employee->roles->role_name }}</option>


What you've done in your controller seems correct. Your view however should loop through the roles and create options for them. Bear in mind, that you've used Role::pluck('role_name', 'id'), which will return an array of 'id' => 'role_name'.

You can decide which one is selected by adding a selected attribute to the employee's role option by using a ternary statement, which compare's the employee's role_id to the role_id we're currently looking at in the loop.

Try something like this:

<select name="roles_id">
    <option value="">Select...</option>
    @foreach ($roles as $roleId => $roleName)
        <option value="{{ $roleId }}"{!! $employee->role_id == $roleId ? ' selected' : '' !!}>{{ $roleName }}</option>