简体   繁体   中英

Laravel - Getting empty dataset when retrieving from DB

I am trying to populate a select dropdown but not seeing the values come through.

Controller:

public function create()
{
    $employees = Employee::get();

    $am = DB::table('employees')
        ->where('department', 'Account Manager')
        ->select('id', 'name')
        ->orderBy('name', 'asc')
        ->get();

    $pm = DB::table('employees')
        ->where('department', 'Project Manager')
        ->select('id', 'name')
        ->orderBy('name', 'asc')
        ->get();

    $employees->am = $am;
    $employees->pm = $pm;

    return view('projects/create', [
        'employees' => $employees
        ]);
}

View:

<div class="form-group">
                  <label>Account Manager</label>
                  <select class="form-control" name="am">
                    <option value=""></option>
                    @foreach ($employees as $employee)
                      <option value="{{ $employee->am['id'] }}">{{ $employee->am['name'] }}</option>
                    @endforeach
                  </select>
                </div>
                <div class="form-group">
                  <label>Project Manager</label>
                  <select class="form-control" name="pm">
                    <option value=""></option>
                    @foreach ($employees as $employee)
                      <option value="{{ $employee->pm['id'] }}">{{ $employee->pm['name'] }}</option>
                    @endforeach
                  </select>
                </div>

So, I know something is working because the dropdowns are showing there are 5 spaces which are the number of records in the DB but they are all blank. Doing a var_dump shows it to be NULL. Also, it is not taking into account the WHERE clause as both dropdowns show 5 spaces rather than 3 for Project Managers and 2 for Account Managers.

My Models do not have any relationship set up. Does it have to? Because I did a join for a different view and it works just fine.

My DB tables look like the following:

Projects:

id
name
am_id
pm_id

Employees:

id
name
department

Any ideas how to have the values populate in the dropdown?

have you tried this?

$employeeAm = Employee::where('department', 'Account Manager')
        ->select('id', 'name')
        ->orderBy('name', 'asc')
        ->get();
$employeePm = Employee::where('department', 'Project Manager')
        ->select('id', 'name')
        ->orderBy('name', 'asc')
        ->get();

then just pass to your view $employeeAm and $employeePm then in your view

@foreach ($employeePm as $employee)
     <option value="{{ $employee->id }}">{{ $employee->name }}</option>
@endforeach

same as for your $employeeAm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM