如何在Laravel中修复未定义的变量错误

时间:2019-04-03 19:45:48

标签: laravel-5

我对此很陌生,如果这是一个愚蠢的问题,我诚挚的道歉!

我的数据库中有两个表-“用户”和“部门”。我正在尝试将“用户”分配给“部门”作为部门经理,并将其user_id存储在部门表中。

我想做的是能够从创建部门表单中的用户下拉菜单中进行选择,但是我仍然收到以下错误:

未定义变量:用户(查看:/home/vagrant/code/PortfolioManager/resources/views/admin/departments/index.blade.php)

有人会知道我要去哪里错吗?我已经尝试解决了2天。

我的部门模型代码如下:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

    class Department extends Model
    {
        protected $fillable = [
            'name',
            'user_id'
        ];

        public function user(){

            return $this->belongsTo('App\User');
        }
    }

我的控制器也在这里:

<?php

namespace App\Http\Controllers;

use App\Department;
use App\Http\Requests\StoreDepartmentRequest;
use App\User;
use Illuminate\Http\Request;

use App\Http\Requests;

class AdminDepartmentsController extends Controller
{
    public function index()
    {
        $departments = Department::all();

        return view('admin.departments.index', compact('departments'));
    }


    public function create()
    {
        $users = User::lists('name', 'id')->all();
        return view('admin.departments.index', compact('users'));
    }


    public function store(StoreDepartmentRequest $request)
    {
        Department::create($request->all());

        return redirect('admin.departments.index');
    }

我的index.blade页面在这里:

<h1>Departments</h1>

<div class="col-sm-6">

    {!! Form::open(['method'=>'POST', 'action'=>'AdminDepartmentsController@store']) !!}

    {{--Name field which is displayed empty--}}
    <div class="form-group">
        {!! Form::label('name', 'Department Name:') !!}
        {!! Form::text('name', null, ['class'=>'form-control']) !!}
    </div>

    <div class="form-group">
        {!! Form::label('user_id', 'Department Manager:') !!}
        {!! Form::select('user_id', ['' => 'Choose Department Manager'] + $users, null, ['class'=>'form-control']) !!}
    </div>

    <div class="form-group">
        {!! Form::submit('Create Business Department', ['class'=>'btn-btn-primary']) !!}
    </div>

    {!! Form::close() !!}


</div>

1 个答案:

答案 0 :(得分:0)

您的创建方法有误...编写以下代码:

public function create()
{
    $users = User::latest()->get();
    return view('admin.departments.index', compact('users'));
}